package org.jeecg.modules.bytedance.advertise.dockapi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.bytedance.advertise.entity.AiBytedanceAdvertiserStrategy;
import org.jeecg.modules.bytedance.advertise.entity.ByteDanceCampaign;
import org.jeecg.modules.bytedance.advertise.service.IAiBytedanceAutocreateLogService;
import org.jeecg.modules.bytedance.advertise.service.IByteDanceCampaignService;
import org.jeecg.modules.bytedance.advertise.vo.AdConvertQueryVo;
import org.jeecg.modules.bytedance.advertise.vo.ByteDanceSearchVo;
import org.jeecg.modules.bytedance.advertise.vo.PlanSearchVo;
import org.jeecg.modules.bytedance.common.constant.BytedanceConstant;
import org.jeecg.modules.bytedance.common.entity.CtopOauthToken;
import org.jeecg.modules.bytedance.common.utils.Check;
import org.jeecg.modules.bytedance.common.utils.HttpUtils;
import org.jeecg.modules.bytedance.common.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 头条-巨量引擎API 接口
 * zianY
 * 2021/4/16
 **/

@Slf4j
@Service
public class MarketingServiceImpl implements MarketingService{
    private  final String urlPath = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url");

    @Autowired
    private IByteDanceCampaignService campaignService;

    @Autowired
    IAiBytedanceAutocreateLogService iBytedanceAutocreateLogService;
    /**
     *
     * @description: 获取账户日预算
     *
     * @param token 授权access_token
     * @param advertiser_ids  广告主id列表，长度限制：[1,100]
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     * @author: zianY
     */
    @Override
    public Result getBudget(CtopOauthToken token, List<Long> advertiser_ids) {
        JSONObject params = new JSONObject();
        //广告主id列表，长度限制：[1,100]
        params.put("advertiser_ids", advertiser_ids);
        //调用api接口--获取账户日预算
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_get_budget"),
                params);
        int code = jsonObject.getInteger("code");
        if (code!=0) {
            log.info("获取账户日预算接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        return Result.successMsg("获取账户日预算成功",jsonObject.get("data"));
    }


    /**
     *
     * @description: 更新账户日预算
     *
     * @param token 授权access_token
     * @param budgetMode 预算模式
     * @param budget 预算值
     * @return: java.util.Map<java.lang.String,java.lang.Object>
     */
    @Override
    public Result updateBudget(CtopOauthToken token, String budgetMode, BigDecimal budget) {
        JSONObject params = new JSONObject();
        //广告主ID
        params.put("advertiser_id", token.getAccountId());
        //预算模式
        // BUDGET_MODE_DAY（日预算）
        //BUDGET_MODE_INFINITE（不限）
        params.put("budget_mode", budgetMode);
        //预算值
        params.put("budget", budget);
        //调用api接口--更新广告主账号设置的预算类型与预算
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_budget"),
                params);
        int code = jsonObject.getInteger("code");
        if (code!=0) {
            log.info("修改计划预算接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        return Result.successMsg("修改账户预算成功",null);
    }




    /**
     *
     * @description: 查询广告主下存在的的人群包列表和信息
     *
     * @param token
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result selectCustomAudience(CtopOauthToken token) {
        JSONObject params = new JSONObject();
        //广告主ID
        params.put("advertiser_id", token.getAccountId());
        //查询类型,枚举值："0"：该广告主创建的人群包和被推送给该广告主的人群包，"1"：状态为可投放的人群包
        params.put("select_type", "1");
        //params.put("offset", "0");
        //params.put("limit", "100");
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_dmp_custom_audience_select"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取人群包信息接口异常==》accountId:{},message:{}", token.getAccountId(), message);
             return Result.error(message);
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("custom_audience_list");
        if (null == data || data.isEmpty()) {
            log.info("人群包信息不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("人群包信息不存在");
        }
        return Result.successMsg("人群包信息获取成功",data);
    }


    /**
     *
     * @description: 获取创意审核建议
     *
     * @param token
     * @param creativeIds 广告创意ID 长度限制：1～10。创意ID需要属于当前广告主，否则会报错。只有审核不通过的创意才有审核建议，审核通过的创意没有审核建议。
     *                    （所有的程序化创意都是审核通过的）
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getCreativeRejectReason(CtopOauthToken token, String creativeIds) {
        JSONObject params = new JSONObject();
        //广告主ID
        params.put("advertiser_id", token.getAccountId());
        //广告创意ID
        params.put("creative_ids", creativeIds);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_create_reject_reason"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取创意审核建议接口异常==》accountId:{},message:{}", token.getAccountId(), message);
             return Result.error(message);
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            log.info("创意审核建议不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("创意审核建议不存在");
        }
        return Result.successMsg("获取创意审核建议成功",data);
    }


    /**
     *
     * @description: 获取创意素材信息
     *
     * @param token
     * @param creativeIds 创意ID集合，支持最大长度为100。创意ID需属于当前广告主，否则会报错
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getMaterialRead(CtopOauthToken token, String[] creativeIds) {

        JSONObject params = new JSONObject();
        //广告主ID
        params.put("advertiser_id", token.getAccountId());
        //创意ID集合
        params.put("creative_ids", creativeIds);
        //查询字段集合, 默认查询所有字段
        //String[] fields={"id", "ad_id", "advertiser_id", "title", "image_info","image_mode", "opt_status"};
        //params.put("fields",fields);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_material_get"),
                params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.error("获取广告主创意素材信息接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("获取广告主创意素材信息接口异常");
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.isEmpty()) {
            return Result.successMsg("获取广告主预算信息为空。",null);
        }
        return Result.successMsg("获取广告主预算信息完成",jsonObject.get("data"));
    }




    /**
     *
     * @description: 修改创意状态
     *
     * @param token
     * @param creativeIds  创意ID列表，长度限制1～100；创意ID需属于广告主，否则会报错！
     * @param optStatus 操作, "enable"表示启用, "disable"表示暂停
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updateCreativeStatus(CtopOauthToken token, String[] creativeIds, String optStatus) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("creative_ids", creativeIds);
        params.put("opt_status", optStatus);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_update_status"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("修改创意状态接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("修改创意状态接口异常。");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data || data.isEmpty()) {
            log.info("修改创意状态返回数据为空==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("修改创意状态返回数据为空。");
        }
        JSONArray ids = data.getJSONArray("creative_ids");
        return Result.successMsg("创意状态修改成功。",ids);
    }




    /**
     *
     * 创建广告组
     * @param token 授权信息
     * @param params 广告组名称
     * @return org.jeecg.common.api.vo.Result
     */
    @Override
    public  Result createCampaign(CtopOauthToken token, JSONObject params) {
        // api创建组
        JSONObject data = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath+PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_create"),
                params);
        if(data == null){
            log.error("创建广告组异常=>param:{}",params.toJSONString());
            return Result.error("头条API创建广告组异常");
        }
        Integer code = data.getInteger("code");
        String message = data.getString("message");
        if(null == code||!code.equals(0)){
            log.error("创建广告组数据异常=>{},parmas:{}",message,params.toJSONString());
            return Result.error(message);
        }
        //广告组id
        JSONArray ids = new JSONArray();
        ids.add(data.getJSONObject("data").getLong("campaign_id"));
        this.getCampaignGroupList(token,token.getAccountId().toString(),ids,1,10);
        return Result.successMsg("广告组创建成功",data.getJSONObject("data").getLong("campaign_id"));
    }

    @Override
    public  JSONObject videoCoverSuggest(CtopOauthToken token, JSONObject params){
        // api创建获取视频推荐封面
        JSONObject result = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+PropertiesUtils.getValue("bytedance_config", "bytedance_v2_tools_video_cover_suggest"),
                params);
        if(result == null){
            log.error("获取视频推荐封面异常=>param:{}",params.toJSONString());
            return null;
        }
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if(null == code||!code.equals(0)){
            log.error("获取视频推荐封面异常=>{},parmas:{}",message,params.toJSONString());
            return null;
        }
        //广告组id
        return result.getJSONObject("data");
    }

    /**
     *
     * @description: 创建广告计划
     *
     * @param token
     * @param params 广告组id
     * @param strategy 入参
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result createAdvertiserPlan(CtopOauthToken token, JSONObject params, AiBytedanceAdvertiserStrategy strategy) {
        log.info("创建参数:{}",params.toJSONString());
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_create"), params);
        log.info("广告计划输出返回信息---->>>>>{}",jsonObject);
        Integer code = jsonObject.getInteger("code");
        if (null ==  code || !code.equals(0)) {
            log.error("广告计划创建失败==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        //strategy.setId(jsonObject.getJSONObject("data").getLong("ad_id"));
        return Result.successMsg("广告计划创建成功",jsonObject.getJSONObject("data").getLong("ad_id"));
    }


    /**
     * 创建广告创意
     * @param
     * @param adId 广告计划id
     * @param params 创意入参
     * @return
     */
    @Override
    public  JSONObject creativeCreate(CtopOauthToken token, Long adId, JSONObject params) {
        return HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_create_v2"),
                params);
    }



    /**
     *
     * @description: 创意详细信息
     *
     * @param token
     * @param advertiserId 广告主id
     * @param adId 计划ID
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result creativeRead(CtopOauthToken token, String advertiserId, String adId) {
        JSONObject param = new JSONObject();
        param.put("advertiser_id",advertiserId);
        param.put("ad_id",adId);
        JSONObject data = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath+PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_read"),
                param);
        if(data == null){
            log.error("获取创意详细信息异常=>param:{}",param.toJSONString());
            return Result.error("获取创意详细信息异常");
        }
        Integer code = data.getInteger("code");
        String message = data.getString("message");
        if(null == code||!code.equals(0)){
            log.error("获取创意详细信息异常=>{},parmas:{}",message,param.toJSONString());
            return Result.error(message);
        }
        return Result.successMsg("获取创意详细信息成功",data.getJSONObject("data"));
    }



    /**
     *
     * @description: 获取创意列表信息
     *
     * @param token
     * @param pageNumber
     * @param byteDanceSearchVoList 创意入参信息
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getAdvertiserCreativeByPageNumber(CtopOauthToken token, Integer pageNumber, List<ByteDanceSearchVo> byteDanceSearchVoList) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        if (null != byteDanceSearchVoList){
            params.put("filtering", byteDanceSearchVoList);
        }
        params.put("page", pageNumber + "");
        params.put("page_size",100);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_get"),params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.info("获取广告主广告创意信息接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("获取广告主广告创意信息接口异常");
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            log.info("广告主广告创意信息不存在==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告主广告创意信息不存在");
        }
        return Result.successMsg("获取广告主创意列表成功。",data);
    }


    /**
     *
     * @description: 获取计划审核建议
     *
     * @param token
     * @param advertiserId 广告主ID
     * @param adIds 广告计划 ID，最多传10个广告计划ID
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getRejectReason(CtopOauthToken token, String advertiserId, List<String> adIds) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", advertiserId);
        params.put("ad_ids", adIds);

        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_create_reasion"), params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
//            log.info("获取广告主计划审核建议接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            if (jsonObject.getString("message").toString().contains("ad_ids:[")) {
                JSONArray ad_ids = JSONArray.parseArray(jsonObject.getString("message").toString().split(":")[2]);
                adIds.removeAll(ad_ids.toJavaList(String.class));
                return getRejectReason(token, advertiserId, adIds);
            }
            return Result.error("获取广告主计划审核建议接口异常==》message:"+jsonObject.getString("message"));
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            log.info("获取广告主计划审核建议不存在==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("获取广告主计划审核建议不存在");
        }
        return Result.successMsg("获取广告主计划审核建议成功。", data);
    }


    /**
     *
     * @description: 更新计划出价
     *
     * @param token
     * @param advertiserId 广告主ID
     * @param listMap  ad_id 广告计划ID
     *                 bid 出价，单位“元”，
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updatePlanBid(CtopOauthToken token, String advertiserId, List<Map<String, Object>> listMap) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", advertiserId);
        params.put("data", listMap);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_bid"), params);
        int code = jsonObject.getInteger("code");
        if (code != 0) {
            log.info("修改计划出价接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("修改计划出价接口异常"+jsonObject.getString("message"));
        }
        return Result.successMsg("修改计划出价成功",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 修改计划预算
     *
     * @param token
     * @param advertiserId 广告主ID
     * @param listMap ad_id 广告计划ID
     *                budget 预算，单位：元。
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updatePlanBudget(CtopOauthToken token, String advertiserId, List<Map<String, Object>> listMap) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", advertiserId);
        params.put("data", listMap);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
               urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_budget_plan"), params);
        int code = jsonObject.getInteger("code");
        Map<String, Object> resultMap = new HashMap<>();
        if (code != 0) {
            log.info("修改计划预算接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("修改计划预算接口异常"+jsonObject.getString("message"));
        }
        return Result.successMsg("修改计划预算成功",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 更新计划状态
     *
     * @param token
     * @param adIds 计划ID集合，限制1～100. 广告计划id需属于广告主，否则会报错！
     * @param optStatus 操作, "enable"表示启用计划, "delete"表示删除计划, "disable"表示暂停计划。
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updPlanStatus(CtopOauthToken token, List<Long> adIds, String optStatus) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("ad_ids", adIds);
        params.put("opt_status", optStatus);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_status"),
                params);
        Integer code = jsonObject.getInteger("code");
        if (code != 0) {
            log.error("广告计划更新状态接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告计划更新状态接口异常");
        }
        return Result.successMsg("广告计划状态修改成功",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 获取广告计划
     *
     * @param token
     * @param
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getPlanList(CtopOauthToken token, PlanSearchVo planSearchVo, Integer pageNo, Integer pageSize) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("filtering", planSearchVo);
        params.put("page", pageNo);
        params.put("page_size", pageSize);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_get_plan"),
                params);
        if (Check.isNull(jsonObject)){
            return Result.errorMsg(jsonObject.get("message").toString());
        }
        Integer code = jsonObject.getInteger("code");
        if (code != 0) {
            log.error("获取广告计划接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        return Result.successMsg("获取广告计划成功",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 广告组更新状态
     *
     * @param token
     * @param campaignIds 广告组ID，不超过100个，且广告组ID属于广告主ID否则会报错；
     * @param optStatus 操作, "enable"表示启用, "delete"表示删除, "disable"表示暂停；
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updateCampaignStatus(CtopOauthToken token, List<String> campaignIds, String optStatus) {
        JSONObject params = new JSONObject();
        //广告主id
        params.put("advertiser_id", token.getAccountId());
        params.put("campaign_ids", campaignIds);
        params.put("opt_status", optStatus);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update_status"), params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.info("广告组更新状态接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告组更新状态接口异常");
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新状态操作异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告组更新状态操作异常");
        }
        return Result.successMsg("广告组更新状态成功。",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 获取广告组
     *
     * @param token
     * @param accountId 广告主id
     * @param ids 广告组 入参
     * @param page
     * @param pageSize
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getCampaignGroupList(CtopOauthToken token, String accountId, JSONArray ids, int page, int pageSize) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        JSONObject filtering = new JSONObject();
        if(null!=ids&&!ids.isEmpty()){
            filtering.put("ids",ids);
        }
        params.put("filtering", filtering);
        params.put("page", page);
        params.put("page_size", pageSize);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_get"), params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.error("获取广告组信息接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
//            log.info("获取广告组信息为空==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("获取广告组信息为空");
        }
        for(int i=0;i<data.size();i++){
            JSONObject campaign = data.getJSONObject(i);
            ByteDanceCampaign result = new ByteDanceCampaign(campaign,Long.parseLong(accountId));
            campaignService.saveOrUpdate(result);
        }
        return Result.successMsg("获取广告组信息成功",data);
    }



    /**
     *
     * @description: 修改广告组
     *
     * @param token
     * @param campaignId 广告组id
     * @param modifyTime 时间戳
     * @param campaignName 广告组名称
     * @param budgetMode 广告组预算类型
     * @param budget 广告组预算
     * @return: org.jeecg.common.api.vo.Result
     */
    @Override
    public  Result updateCampaign(CtopOauthToken token, String campaignId, String modifyTime, String campaignName, String budgetMode, String budget) {
        JSONObject params = new JSONObject();
        //广告主id
        params.put("advertiser_id", token.getAccountId());
        //广告组id
        params.put("campaign_id", campaignId);
        //时间戳
        params.put("modify_time", modifyTime);
        //广告组名称
        params.put("campaign_name", campaignName);
        //广告预算类型
        params.put("budget_mode", budgetMode);
        //预算
        params.put("budget", budget);
        // value 为空 则 移除
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update"),
                params);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.info("广告组更新接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告组更新接口异常"+jsonObject.getString("message"));
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error("广告组更新异常"+jsonObject.getString("message"));
        }
        return Result.successMsg("广告组信息修改成功。", data.getString("campaign_id"));
    }


    /**
     *
     * @description: 修改广告计划
     *
     * @param token
     * @param planId 计划id
     * @param modifyTime 计划时间戳
     * @param strategy
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result updateAdvertiserPlan(CtopOauthToken token, String planId, String modifyTime, AiBytedanceAdvertiserStrategy strategy) {
        JSONObject params = new JSONObject();
        //广告主ID
        params.put("advertiser_id", strategy.getAccountId());
        //广告计划ID
        params.put("ad_id", planId);
        params.put("modify_time", modifyTime);
        //广告计划名称
        params.put("name", strategy.getAdName());
        //计划状态 默认值： "enable"开启状态 允许值: "enable"开启,"disable"关闭
        //params.put("operation", BytedanceConstant.OPERATION_ENABLE);
        // 投放范围  "DEFAULT"默认, "UNION"穿山甲
        params.put("delivery_range", strategy.getAdDeliveryRange() == null ? "DEFAULT" : strategy.getAdDeliveryRange());
        if(null!=strategy.getAdDownloadUrl()&&!"".equals(strategy.getAdDownloadUrl().trim())){
            params.put("download_url", strategy.getAdDownloadUrl());
        }
        //投放形式（穿山甲视频创意类型） 当delivery_range为"UNION"时必填
        // 允许值: "ORIGINAL_VIDEO"原生, "REWARDED_VIDEO"激励视频,"SPLASH_VIDEO"开屏
        // params.put("union_video_type", byteDanceAdvertisePlan.getUnionVideoType() == null ? "ORIGINAL_VIDEO" : byteDanceAdvertisePlan.getUnionVideoType());
        //投放内容
        //推广目的 为应用推广（landing_type=APP）时投放目标参数
        if ("APP".equalsIgnoreCase(strategy.getCampaignLandingType())) {
            //下载方式  可选值：DOWNLOAD_URL下载链接，QUICK_APP_URL快应用+下载链接，EXTERNAL_URL落地页链接
            params.put("download_type", strategy.getAdDownloadType());
            //下载链接
            // 类型为下载链接
//            if ("DOWNLOAD_URL".equals(strategy.getAdDownloadType())){
//                params.put("download_url", strategy.getAdDownloadUrl());
//                //下载的应用类型,当download_type为DOWNLOAD_URL时必填
//                //允许值: "APP_ANDROID"Android APP, "APP_IOS"IOS APP
//                params.put("app_type", strategy.getAdAppType());
//                params.put("package", strategy.getAdPackage());
//            }
            // 类型为 快应用+下载链接
            if ("QUICK_APP_URL".equals(strategy.getAdDownloadType())){
                params.put("quick_app_url", strategy.getAdDownloadUrl());
            }
            // 类型为落地页链接
            if ("EXTERNAL_URL".equals(strategy.getAdDownloadType())){
                params.put("external_url", strategy.getAdDownloadUrl());
            }
        }
        //转化目标
        params.put("convert_id", strategy.getAdConvertId());
        //直达链接(点击唤起APP)
        params.put("open_url", strategy.getAdOpenUrl());
        //搜索快投功能，允许值：HAS_OPEN:启用，DISABLED:不启用
        //params.put("feed_delivery_search", "搜索快投");
        //用户定向
        params.put("audience_package_id",strategy.getAdAudiencePackageId());
        //允许值: "CITY"省市, "COUNTY"区县, "BUSINESS_DISTRICT"商圈,"NONE"不限
        params.put("district", strategy.getAdScheduleType());
        //性别 允许值: "GENDER_FEMALE", "GENDER_MALE", "NONE"
        params.put("gender", strategy.getAdGender());
        //允许值: "AGE_BETWEEN_18_23", "AGE_BETWEEN_24_30","AGE_BETWEEN_31_40", "AGE_BETWEEN_41_49", "AGE_ABOVE_50"
        //年龄不限 不传该字段
        params.put("age", strategy.getAdAge());
        //自定义人群 不限 不传该字段
        // 定向人群包列表（自定义人群）
        params.put("retargeting_tags_include",strategy.getAdRetargetingTagsInclude());
        //排除人群包列表（自定义人群）
        params.put("retargeting_tags_exclude",strategy.getAdRetargetingTagsExclude());
        //媒体定向
        params.put("superior_popularity_type", strategy.getAdSuperiorPopularityType());
        //平台
        params.put("platform", strategy.getAdPlatform());
        //最低安卓版本
        params.put("android_osv", strategy.getAdAndroidOsv());
        //网络
        params.put("ac", strategy.getAdAc());
        //过滤已安装  当推广目标为安卓应用下载时可填 0表示不限，1表示过滤，2表示定向。默认为不限
        params.put("hide_if_exists", strategy.getAdHideIfExists());
        //过滤已转化用户 NO_EXCLUDE-不过滤;AD-广告计划(默认);CAMPAIGN-广告组; ADVERTISER-广告账户; APP-APP; CUSTOMER-公司账户
        params.put("hide_if_converted", strategy.getAdHideIfConverted());
        //是否启用智能放量 0、1。缺省为 0
        params.put("auto_extend_enabled", strategy.getAdAutoExtendEnabled());
        //预算与出价
        //投放场景 允许值: 常规投放"SMART_BID_CUSTOM", 放量投放"SMART_BID_CONSERVATIVE"
        params.put("smart_bid_type", strategy.getAdSmartBidType());
        //预算类型 "BUDGET_MODE_DAY"日预算, "BUDGET_MODE_TOTAL"总预算
        params.put("budget_mode", strategy.getAdBudgetMode());
        //预算 出价方式为CPC、CPM、CPV时，不少于100元；出价方式为OCPM、OCPC时，不少于300元
        params.put("budget", strategy.getAdBudget());
        //投放时间类型 允许值: "SCHEDULE_FROM_NOW"从今天起长期投放, "SCHEDULE_START_END"设置开始和结束日期
        params.put("schedule_type", strategy.getAdScheduleType());
        //投放时段，默认全时段投放
        params.put("schedule_time", strategy.getAdScheduleTime());
        //付费方式（计划出价类型） 决定投放目标的类型，比如CPC表示点击量，OCPM表示转化量
        params.put("pricing", strategy.getAdPricing());
        //params.put("pricing", "PRICING_OCPM");
        //目标转化出价/预期成本， 当pricing为"OCPM"、"OCPC"出价方式时必填）
        //pricing为"OCPC"时取值范围：0.1-10000元；
        //pricing为"OCPM"时取值范围：0.1-10000元；
        //出价不能大于预算否则会报错
        params.put("cpa_bid", strategy.getAdCpaBid());
        //params.put("bid", strategy.getAdCpaBid());
        params = Check.jsonRemoveEmpty(params);
        System.out.println(params.toJSONString());
        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update"), params);
        System.out.println(jsonObject.toJSONString());
        Integer code = jsonObject.getInteger("code");
        if (null ==  code || !code.equals(0)) {
            log.error("广告计划修改失败==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return Result.error(jsonObject.getString("message"));
        }
        //byteDanceAdvertisePlan.setId(jsonObject.getJSONObject("data").getLong("ad_id"));
        return Result.successMsg("广告计划修改成功",jsonObject.getString("data"));
    }


    /**
     *
     * @description: 修改广告创意信息
     *
     * @param token
     * @param adId 广告计划id
     * @param modifyTime 时间戳
     * @param data
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result creativeUpdate(CtopOauthToken token, String adId, String modifyTime, JSONObject data) {
       //广告主ID
        data.put("advertiser_id", token.getAccountId());
        //广告计划ID
        data.put("ad_id", adId);
        //时间戳
        data.put("modify_time", modifyTime);
        //广告 投放位置 三选一
        if (!data.getString("smart_inventory").isEmpty()){
            //优选广告位，0表示不使用优选，1表示使用
            data.put("smart_inventory", data.getString("smart_inventory"));
        }
        if (!data.getString("inventory_type").isEmpty()){
            //广告位置（按媒体指定位置）
            data.put("inventory_type", data.getString("inventory_type"));
        }
        if (!data.getString("scene_inventory").isEmpty()){
            //场景广告位
            data.put("scene_inventory", data.getString("scene_inventory"));
        }
        //监测链接
        data.put("action_track_url", data.getString("action_track_url"));
        //创意方式，当值为"_ASSEMBLE"表示程序化创意，其他情况不传字段
        data.put("creative_material_mode", data.getString("creative_material_mode"));
        //标题信息
        data.put("image_list", data.getJSONArray("image_list"));
        //行动号召
        data.put("action_text", data.getString("action_text"));
        //是否使用智能优选，true为使用，false为不使用
        data.put("enable_personal_action", data.getString("enable_personal_action"));
        //卡片标题
        data.put("product_description", data.getString("product_description"));
        //推广卖点 长度6-9个字，最多可填10个卖点
        data.put("product_selling_points", data.getString("product_selling_points"));
        //来源
        data.put("source", data.getString("source"));
        //创意分类
        data.put("third_industry_id", data.getString("third_industry_id"));
        //创意标签 创意标签。最多20个标签，且每个标签长度不超过10个字符
        data.put("ad_keywords", data.getString("ad_keywords"));
        data = Check.jsonRemoveEmpty(data);
        JSONObject result = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_update_v2"),
                data);
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null == code || code != 0) {
            return Result.error("广告计划("+adId+"):修改创意信息异常--->>>"+message);
        }
        return Result.successMsg("广告计划("+adId+"):"+"创意修改成功",null);
    }







    /**
     *
     * @description: 获取行业列表
     *
     * @param token
     * @param type  "ADVERTISER"为原有广告3.0行业, "AGENT"为代理商行业获取，代理商行业level都为1
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getToolIndustryList(CtopOauthToken token, String type) {

        JSONObject params = new JSONObject();
        params.put("type", type);
        params.put("level",type.equalsIgnoreCase(BytedanceConstant.LEVEL_AGENT) ? 1 : "");
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_tools_industry_get"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取行业类别信息接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            log.info("行业类别信息不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("行业类别信息不存在");
        }

        return Result.successMsg("行业类别信息获取成功",data);
    }


    /**
     *
     * @description: 查询广告计划可用转化目标
     *
     * @param token
     * @param convertQueryVo
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getToolConvertQuery(CtopOauthToken token, AdConvertQueryVo convertQueryVo) {

        JSONObject params = new JSONObject();
        //广告主id
        params.put("advertiser_id",convertQueryVo.getAdvertiserId());
        //广告组推广目的
        params.put("landing_type", convertQueryVo.getLandingType());
        //营销目的
        params.put("marketing_purpose", "CONVERSION");
        params.put("campaign_type", "FEED");
        //投放内容
        params.put("promotion_content", convertQueryVo.getPromotionContent());
        //落地页链接
        params.put("external_url", convertQueryVo.getExternalUrl());
        //应用下载类型
        params.put("app_type", convertQueryVo.getAppType());
        //Android应用包名
        params.put("package_name", convertQueryVo.getPackageName());
        //iOS应用下载链接
        params.put("itunes_url", convertQueryVo.getItunesUrl());
        //小程序app_schema
        params.put("app_schema", convertQueryVo.getAppSchema());
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_tools_ad_convert_optimized_target"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("查询广告计划可用转化目标接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONArray dataList = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == dataList || dataList.isEmpty()) {
            log.info("查询广告计划可用转化目标不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("账户优化目标不存在！");
        }
        for (Object obj : dataList){
            JSONObject json = (JSONObject)obj;
            JSONArray arrayConverts = json.getJSONArray("converts");
            for (Object convert : arrayConverts){
                JSONObject con = (JSONObject)convert;
                JSONArray actions = con.getJSONArray("external_actions");
                if (!Check.isNull(actions)){
                    return Result.successMsg("查询广告计划可用优化目标信息获取成功",dataList);
                }
            }
        }
        return Result.successMsg("查询广告计划暂时无可用优化目标",dataList);
    }

    /**
     * 查询转化目标详细信息
     * @param token
     * @param accountId
     * @param convertId
     * @return
     */
    @Override
    public  Result readToolConvertInfo(CtopOauthToken token, String accountId,String convertId) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id",accountId);
        params.put("convert_id", convertId);
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_tools_ad_convert_read"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("查询查询转化目标详细信息接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONObject dataList = jsonObject.getJSONObject("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("查询查询转化目标详细信息不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("查询转化目标详细信息不存在！");
        }
        return Result.successMsg("查询转化目标详细信息不存在",dataList);
    }


    /**
     *  上传平台 图片
     * @param token
     * @param imageUrl 图片url
     * @return
     */
    @Override
    public  JSONObject imageUpload(CtopOauthToken token, String imageUrl) {
        // 请求地址
        String url = urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_file_image_ad");
        // 构造请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Access-Token", token.getAccessToken());
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        // 其他参数
        entityBuilder.addTextBody("advertiser_id", token.getAccountId().toString());
        entityBuilder.addTextBody("upload_type", BytedanceConstant.UPLOAD_TYPE_BY_URL);
        entityBuilder.addTextBody("image_url", imageUrl);

        HttpEntity entity = entityBuilder.build();
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClientBuilder.create().build();
            httpPost.setURI(URI.create(url));
            httpPost.setEntity(entity);
            response = client.execute(httpPost);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder buffer = new StringBuilder();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);
                }
                bufferedReader.close();
                return JSONObject.parseObject(buffer.toString());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (null != client) {
                    client.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    @Override
    public  JSONObject getSuggestImageId(CtopOauthToken token, String vid) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/tools/video_cover/suggest/";
        // 请求参数
        JSONObject data = new JSONObject();
        data.put("advertiser_id", token.getAccountId());
        data.put("video_id", vid);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(),url,data);
    }


    /**
     *
     * @description: 行动号召字段内容获取
     *
     * @param token
     * @param landingType  推广类型
     * @param advancedCreativeType 附加创意类型
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result getActionText(CtopOauthToken token, String landingType,String advancedCreativeType) {

        JSONObject data = new JSONObject();
        data.put("advertiser_id", token.getAccountId());
        data.put("landing_type", landingType);
        data.put("advanced_creative_type", advancedCreativeType);
        //data.put("industry", "");
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_tools_action_text_get"),data);

        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");

        if (null == code || !code.equals(0)) {
            log.info("行动号召字段内容获取接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONArray dataList = jsonObject.getJSONArray("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("行动号召字段内容获取不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("行动号召字段内容获取");
        }
        return Result.successMsg("获取行动号召成功",dataList);
    }



    /**
     *
     * @description: 获取定向包
     *
     * @param token
     * @param landingType 定向包类型
     * @param deliveryRange 广告投放范围
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getAudiencePackage(CtopOauthToken token,String landingType,String deliveryRange) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        Map map = new HashMap();
        map.put("landing_type",landingType);
        map.put("delivery_range",deliveryRange);
        params.put("filtering", map);
        params.put("page", 1);
        params.put("page_size", 100);
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_audience_package_get"),params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取定向包接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONObject dataList = jsonObject.getJSONObject("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("获取定向包不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("获取定向包不存在");
        }
        return Result.successMsg("获取定向包成功",dataList);
    }



    /**
     *
     * @description: 获取人群包详细信息
     *
     * @param token
     * @param accountId
     * @param ids
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     * @time: 2021/5/12 11:16
     */
    @Override
    public Result getAudiencePackageRead(CtopOauthToken token,String accountId,List<Integer> ids) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("custom_audience_ids", ids);
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_dmp_custom_audience_read"),params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取人群包详细信息接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONObject dataList = jsonObject.getJSONObject("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("获取人群包详细信息不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("获取人群包详细信息不存在");
        }
        return Result.successMsg("获取人群包详细信息成功",dataList.getJSONArray("custom_audience_list"));
    }


    /**
     *
     * @description: 创建定向包
     *
     * @param token
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public  Result createAudiencePackage(CtopOauthToken token) {

        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("name", "测试-定向包创建-004");
        params.put("description", "0512定向包-过滤已转化用户-测试");
        params.put("landing_type", "APP_ANDROID");
        params.put("hide_if_exists", 2);
        params.put("hide_if_converted", "AD");

        JSONObject jsonObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),
                urlPath + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_audience_package_create"),
                params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("创建定向包接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        return Result.successMsg("创建定向包成功",jsonObject.getJSONObject("audience_package_id"));
    }

    /**
     *
     * @description: 获取橙子建站站点列表
     * @param token
     * @return: org.jeecg.common.api.vo.Result
     * @author: zianY
     */
    @Override
    public Result getSite(CtopOauthToken token) {
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("status", "SITE_ONLINE");
        params.put("page", 1);
        params.put("page_size", 300);
        params.put("filtering", null);
        params = Check.jsonRemoveEmpty(params);
        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_site_get"),params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取橙子建站站点列表接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONObject dataList = jsonObject.getJSONObject("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("获取橙子建站站点列表不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("获取橙子建站站点列表不存在");
        }
        return Result.successMsg("获取橙子建站站点列表成功",dataList.getJSONArray("list"));

    }

    @Override
    public Result getCreativeComponent(CtopOauthToken token) {

        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("page", 1);
        params.put("page_size", 40);
        params.put("filtering", null);
        params = Check.jsonRemoveEmpty(params);

        JSONObject jsonObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(),
                urlPath+ PropertiesUtils.getValue("bytedance_config", "bytedance_v2_assets_get"),params);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("查询组件列表接口异常==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error(message);
        }
        JSONObject dataList = jsonObject.getJSONObject("data");
        if (null == dataList || dataList.isEmpty()) {
            log.info("查询组件列表不存在==》accountId:{},message:{}", token.getAccountId(), message);
            return Result.error("查询组件列表不存在");
        }
        return Result.successMsg("查询组件列表成功",dataList.getJSONArray("list"));
    }


}