package cn.com.ctop.toutiao.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.toutiao.entity.*;
import cn.com.ctop.toutiao.service.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author 宋英豪
 */
@Slf4j
@Service
public class ByteDanceAdvertiserDataServiceImpl implements IByteDanceAdvertiserDataService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceAdvertisePlanService advertisePlanService;
    @Autowired
    private IByteDanceCreativeMaterialService creativeMaterialService;
    @Autowired
    private IByteDanceAdvertiserBudgetService advertiserBudgetService;
    @Autowired
    private IByteDanceCampaignService campaignService;
    @Autowired
    private IByteDanceAdvertiserService advertiserService;
    @Autowired
    private IByteDanceImageInfoService imageInfoService;
    @Autowired
    private IByteDanceVideoInfoService videoInfoService;

    @Override
    public Map<String, Object> getAdvertiserInfo(String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_advertiser_info");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());
        TreeMap<String, Object> params = new TreeMap<>();
        //TODO jsonArray
        params.put("advertiser_ids", "[" + cTopOauthToken.getAccountId() + "]");
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("获取广告主信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", "获取广告主信息接口异常");
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.size() <= 0) {
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", "广告主信息不存在");
            return resultMap;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            resultMap.put("name", dataObject.getString("name"));
        }
        resultMap.put("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告主信息成功");
        return resultMap;
    }

    public void getAd(String accountId, int pageNum, String ids, String date) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        String[] idString = ids.split(StringUtils.COMMA);
        JSONArray getIds = new JSONArray();
        if (null != idString && idString.length > 0) {
            for (int i = 0; i < idString.length; i++) {
                Long getId = Long.parseLong(idString[i]);
                getIds.add(getId);
            }
        }

        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/ad/get/";
        // 请求参数
        Map<String, Object> filtering = new HashMap<>();
        if (null != getIds && getIds.size() > 0) {
            filtering.put("ids", getIds);
        }
        if (null != date && !"".equals(date)) {
            filtering.put("ad_create_time", date);
        }

        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page", pageNum);
        param.put("page_size", 100);
        param.put("filtering", filtering);
        log.info("查询广告计划信息参数：{}", param.toJSONString());
        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
        log.info("获取公告计划信息返回数据：{}", resultObject.toJSONString());
        Integer code = resultObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.error("获取广告计划信息接口异常==》accountId:{},message:{}", accountId, resultObject.getString("message"));
            return;
        }
        JSONArray data = resultObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.error("获取广告计划信息不存在==》accountId:{},message:{}", accountId, resultObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceAdvertisePlan advertisePlan = new ByteDanceAdvertisePlan(dataObject, accountId);
            advertisePlanService.saveOrUpdate(advertisePlan);
        }
        getAd(accountId, pageNum + 1, ids, date);
    }

    @Override
    public Map<String, Object> getAdvertiserPlan(String accountId, String ids, String date) {
        getAd(accountId, 1, ids, date);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告计划信息成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdvertiserCampaign(String accountId, String ids, String date) {
        getAdvertiserCampaignByPageNumber(accountId, 1, ids, date);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告組信息成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdvertiserBudget(String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_get");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("advertiser_ids", "[" + cTopOauthToken.getAccountId() + "]");
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("获取广告预算信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "获取广告预算信息接口异常");
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.size() <= 0) {
            log.info("广告主预算信息不存在==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", 0);
            resultMap.put("message", "获取广告主预算信息完成");
            return resultMap;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceAdvertiserBudget advertiserBudget = new ByteDanceAdvertiserBudget(dataObject, accountId);
            advertiserBudgetService.saveOrUpdate(advertiserBudget);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告预算信息完成");
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdvertiserCreativeMaterial(String accountId, String creativeIds) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_material_get");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        if (null != creativeIds && !"".equals(creativeIds.trim())) {
            params.put("creative_ids", "[" + creativeIds + "]");
        }
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("获取广告主创意素材信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "获取广告主创意素材信息接口异常");
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.size() <= 0) {
            log.info("广告主创意素材信息不存在==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", 0);
            resultMap.put("message", "获取广告主预算信息完成");
            return resultMap;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCreativeMaterial material = new ByteDanceCreativeMaterial(dataObject, accountId);
            creativeMaterialService.saveOrUpdate(material);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告主预算信息完成");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserCampaignUpdateStatus(String accountId, String campaignIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray ids = new JSONArray();
        String[] getIds = campaignIds.split(StringUtils.COMMA);
        if (null != getIds && getIds.length > 0) {
            for (int i = 0; i < getIds.length; i++) {
                ids.add(Long.parseLong(getIds[i]));
            }
        }
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update_status");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("campaign_ids", ids);
        params.put("opt_status", optStatus);
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("广告组更新状态接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组更新状态接口异常");
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新状态异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组更新状态异常");
            return resultMap;
        }
        JSONArray getCampaignIds = data.getJSONArray("campaign_ids");
        if (null != getCampaignIds && getCampaignIds.size() > 0) {
            for (int i = 0; i < getCampaignIds.size(); i++) {
                Long id = getCampaignIds.getLong(i);
                ByteDanceCampaign campaign = campaignService.getById(id);
                if (null != campaign) {
                    campaign.setOptStatus(optStatus);
                }
                campaignService.updateById(campaign);
            }
        }
        resultMap.put("code", 0);
        resultMap.put("message", "广告组状态修改成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserCampaignUpdate(String accountId, Long campaignId, String budgetMode, Integer budget, String campaignName) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        ByteDanceCampaign campaign = campaignService.getById(campaignId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("campaign_id", campaignId);
        params.put("modify_time", campaign.getModifyTime());
        if (null != campaignName && !"".equals(campaignName.trim())) {
            params.put("campaign_name", campaignName);
        }
        if (null != budgetMode && !"".equals(budgetMode.trim())) {
            params.put("budget_mode", budgetMode);
        }
        if (null != budget) {
            params.put("budget", budget);
        }
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("广告组更新接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组更新接口异常");
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组更新异常");
            return resultMap;
        }
        if (null != campaignName && !"".equals(campaignName.trim())) {
            campaign.setName(campaignName);
        }
        if (null != budgetMode && !"".equals(budgetMode.trim())) {
            params.put("budget_mode", budgetMode);
            campaign.setBudgetMode(budgetMode);
        }
        if (null != budget) {
            campaign.setBudget(new BigDecimal(budget));
        }
        campaignService.updateById(campaign);

        resultMap.put("code", 0);
        resultMap.put("message", "广告组信息修改成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserPlanUpdateStatus(String accountId, String adIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray ids = new JSONArray();
        String[] getIds = adIds.split(StringUtils.COMMA);
        if (null != getIds && getIds.length > 0) {
            for (int i = 0; i < getIds.length; i++) {
                ids.add(Long.parseLong(getIds[i]));
            }
        }
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_status");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("ad_ids", ids.toJSONString());
        params.put("opt_status", optStatus);
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.error("广告计划更新状态接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告计划更新状态接口异常");
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告计划更新状态异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告计划更新状态异常");
            return resultMap;
        }
        JSONArray getAdIds = data.getJSONArray("ad_ids");
        if (null != getAdIds && getAdIds.size() > 0) {
            //获取广告计划信息
            getAdvertiserPlan(accountId, adIds, null);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "广告组状态修改成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserPlanUpdateBid(String accountId, String adIds, String bids) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray data = new JSONArray();
        String[] getadIds = adIds.split(StringUtils.COMMA);
        String[] getBids = bids.split(StringUtils.COMMA);
        if (null != getadIds && getadIds.length > 0) {
            for (int i = 0; i < getadIds.length; i++) {
                JSONObject object = new JSONObject();
                Long adId = Long.parseLong(getadIds[i]);
                Long bid = Long.parseLong(getBids[i]);
                object.put("ad_id", adId);
                object.put("bid", bid);
                data.add(object);
            }
        }
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_bid");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("data", data.toJSONString());
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("修改计划出价接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划出价接口异常");
            return resultMap;
        }
        JSONObject getData = jsonObject.getJSONObject("data");
        if (null == getData) {
            log.info("修改计划出价异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划出价异常");
            return resultMap;
        }
        JSONArray getAdIds = getData.getJSONArray("ad_ids");
        if (null != getAdIds && getAdIds.size() > 0) {
            //获取广告计划信息
            getAdvertiserPlan(accountId, adIds, null);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "修改计划出价成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserPlanUpdateBudget(String accountId, String adIds, String budgets) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray data = new JSONArray();
        String[] getadIds = adIds.split(StringUtils.COMMA);
        String[] getBudgets = budgets.split(StringUtils.COMMA);
        if (null != getadIds && getadIds.length > 0) {
            for (int i = 0; i < getadIds.length; i++) {
                JSONObject object = new JSONObject();
                Long adId = Long.parseLong(getadIds[i]);
                Long budget = Long.parseLong(getBudgets[i]);
                object.put("ad_id", adId);
                object.put("budget", budget);
                data.add(object);
            }
        }
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_update_budget");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("data", data.toJSONString());
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.info("修改计划预算接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划预算接口异常");
            return resultMap;
        }
        JSONObject getData = jsonObject.getJSONObject("data");
        if (null == getData) {
            log.info("修改计划预算异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划预算异常");
            return resultMap;
        }
        JSONArray getAdIds = getData.getJSONArray("ad_ids");
        if (null != getAdIds && getAdIds.size() > 0) {
            //获取广告计划信息
            getAdvertiserPlan(accountId, adIds, null);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "修改计划预算成功");
        return resultMap;
    }

    /**
     * 查询人群包信息
     *
     * @return
     */
    @Override
    public Map<String, Object> advertiserCustomAudienceSelect(String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);

        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_dmp_custom_audience_select");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("select_type", "0");
        params.put("advertiser_id", token.getAccountId() + "");
        params.put("limit", "100");
        params.put("offset", "0");
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("获取人群包信息接口异常==》accountId:{},message:{}", token.getAdvertiserId(), jsonObject.getString("message"));
            resultMap.put("success", false);
            resultMap.put("message", "获取人群包信息接口异常");
            resultMap.put("code", -1);
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("custom_audience_list");
        if (null == data || data.size() <= 0) {
            log.info("人群包信息不存在==》accountId:{},message:{}", token.getAdvertiserId(), jsonObject.getString("message"));
            resultMap.put("success", false);
            resultMap.put("message", "人群包信息不存在");
            resultMap.put("code", -1);
            return resultMap;
        }
        resultMap.put("success", true);
        resultMap.put("message", "人群包信息获取成功");
        resultMap.put("data", data);
        resultMap.put("code", 0);
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserAdUpdate(String accountId, Long adId, ByteDanceUserOrientationTemplate template) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        return null;
    }

    @Override
    public JSONObject updateAd(CtopOauthToken token, Long adId, ByteDanceUserOrientationTemplate template, JSONObject requestJson) {

        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/ad/update/";
        // 请求参数
        JSONObject data = new JSONObject();
        data.put("advertiser_id", token.getAccountId());
        data.put("ad_id", adId);
        data = setUserOrentationData(data, template, adId, requestJson);
        return HttpUtils.bytedancePostRequest(token.getAccessToken(), url, data);
    }

    @Override
    public JSONObject setUserOrentationData(JSONObject data, ByteDanceUserOrientationTemplate template, Long adId, JSONObject requestJson) {
        //根据adId获取公告计划信息
        ByteDanceAdvertisePlan advertisePlan = advertisePlanService.getById(adId);
        data.put("modify_time", advertisePlan.getModifyTime());
        Integer deliveryType = requestJson.getInteger("deviceType");
        if (null != deliveryType && deliveryType == 2) {
            //穿山甲
            //精选流量包类型
            String superiorPopularityType = template.getSuperiorPopularityType();
            if (null != superiorPopularityType && "ZDY".equals(superiorPopularityType)) {
                JSONArray flowPackage = requestJson.getJSONArray("flowPackage");
                if (null != flowPackage && flowPackage.size() > 0) {
                    JSONArray getFlowPackage = new JSONArray();
                    for (int i = 0; i < flowPackage.size(); i++) {
                        String flowPackageString = flowPackage.getString(i);
                        getFlowPackage.add(Long.parseLong(flowPackageString));
                    }
                    data.put("flow_package", getFlowPackage);
                }
                JSONArray excludeFlowPackage = requestJson.getJSONArray("excludeFlowPackage");
                if (null != excludeFlowPackage && excludeFlowPackage.size() > 0) {
                    JSONArray getExcludeFlowPackage = new JSONArray();
                    for (int i = 0; i < excludeFlowPackage.size(); i++) {
                        String excludeFlowPackageString = excludeFlowPackage.getString(i);
                        getExcludeFlowPackage.add(Long.parseLong(excludeFlowPackageString));
                    }
                    data.put("exclude_flow_package", getExcludeFlowPackage);
                }
            } else {
                data.put("superior_popularity_type", superiorPopularityType);
            }
            //设备类型
            String deviceType = template.getDeviceType();
            if (null != deviceType && !"".equals(deviceType) && !"NONE".equals(deviceType)) {
                JSONArray typeArray = new JSONArray();
                typeArray.add(deviceType);
                data.put("device_type", typeArray);
            }
        }

        JSONArray retargetingTagsExclude = requestJson.getJSONArray("retargetingTagsExclude");
        JSONArray retargetingTagsInclude = requestJson.getJSONArray("retargetingTagsInclude");
        if (null != retargetingTagsExclude && retargetingTagsExclude.size() > 0) {
            JSONArray getRetargetingTagsExclude = new JSONArray();
            for (int i = 0; i < retargetingTagsExclude.size(); i++) {
                String exclude = retargetingTagsExclude.getString(i);
                getRetargetingTagsExclude.add(Long.parseLong(exclude));
            }
            data.put("retargeting_tags_exclude", getRetargetingTagsExclude);
        }
        if (null != retargetingTagsInclude && retargetingTagsInclude.size() > 0) {
            JSONArray getRetargetingTagsInclude = new JSONArray();
            for (int i = 0; i < retargetingTagsInclude.size(); i++) {
                String include = retargetingTagsInclude.getString(i);
                getRetargetingTagsInclude.add(Long.parseLong(include));
            }
            data.put("retargeting_tags_include", getRetargetingTagsInclude);
        }
        data = setUserOrentationData(data, template);
        return data;
    }

    @Override
    public JSONObject setUserOrentationData(JSONObject data, ByteDanceUserOrientationTemplate template) {
        //根据adId获取公告计划信息
        if (null != template.getGender() && !"".equals(template.getGender().trim())) {
            data.put("gender", template.getGender());
        }
        if (null != template.getAge() && !"".equals(template.getAge().trim())) {
            JSONArray ageArray = JSONArray.parseArray(template.getAge());
            data.put("age", ageArray);
        }
        if (null != template.getAndroidOsv() && !"".equals(template.getAndroidOsv().trim())) {
            data.put("android_osv", template.getAndroidOsv());
        }
        if (null != template.getIosOsv() && !"".equals(template.getIosOsv().trim())) {
            data.put("ios_osv", template.getIosOsv());
        }
        if (null != template.getCarrier() && !"".equals(template.getCarrier().trim())) {
            JSONArray carrierArray = JSONArray.parseArray(template.getCarrier());
            data.put("carrier", carrierArray);
        }
        if (null != template.getAc() && !"".equals(template.getAc().trim())) {
            JSONArray acArray = JSONArray.parseArray(template.getAc());
            data.put("ac", acArray);
        }
        if (null != template.getDeviceBrand() && !"".equals(template.getDeviceBrand().trim())) {
            JSONArray deviceBrandArray = JSONArray.parseArray(template.getDeviceBrand());
            data.put("device_brand", deviceBrandArray);
        }
        if (null != template.getArticleCategory() && !"".equals(template.getArticleCategory().trim())) {
            JSONArray articleCategoryArray = JSONArray.parseArray(template.getArticleCategory());
            data.put("article_category", articleCategoryArray);
        }
        if (null != template.getActivateType() && !"".equals(template.getActivateType().trim())) {
            JSONArray activateTypeArray = JSONArray.parseArray(template.getActivateType());
            data.put("activate_type", activateTypeArray);
        }
        if (null != template.getPlatform() && !"".equals(template.getPlatform().trim())) {
            JSONArray platformArray = new JSONArray();
            platformArray.add(template.getPlatform());
            data.put("platform", platformArray);
        }
        if (null != template.getBusinessIds() && !"".equals(template.getBusinessIds().trim())) {
            JSONArray bussinessIdArray = JSONArray.parseArray(template.getBusinessIds());
            data.put("business_ids", bussinessIdArray);
        }
        if (null != template.getAreaType() && !"".equals(template.getAreaType().trim())) {
            data.put("district", template.getAreaType());
            if ("CITY".equals(template.getAreaType())) {
                JSONArray cityArray = JSONArray.parseArray(template.getCity());
                data.put("city", cityArray);
            } else if ("COUNTY".equals(template.getAreaType())) {
                JSONArray countyArray = JSONArray.parseArray(template.getDistrict());
                data.put("city", countyArray);
            }

        }

        if (null != template.getLocationType() && !"".equals(template.getLocationType().trim())) {
            data.put("location_type", template.getLocationType());
        }
        if (null != template.getAdTag() && !"".equals(template.getAdTag().trim())) {
            JSONArray adTagArray = JSONArray.parseArray(template.getAdTag());
            data.put("ad_tag", adTagArray);
        }
        if (null != template.getInterestTags() && !"".equals(template.getInterestTags().trim())) {
            JSONArray interestTagArray = JSONArray.parseArray(template.getInterestTags());
            data.put("interest_tags", interestTagArray);
        }
        if (null != template.getAppBehaviorTarget() && !"".equals(template.getAppBehaviorTarget().trim())) {
            data.put("app_behavior_target", template.getAppBehaviorTarget());
        }
        if (null != template.getAppCategory() && !"".equals(template.getAppCategory().trim())) {
            JSONArray appCategoryArray = JSONArray.parseArray(template.getAppCategory());
            data.put("app_category", appCategoryArray);
        }
        if (null != template.getAppIds() && !"".equals(template.getAppIds().trim())) {
            JSONArray appIdsArray = JSONArray.parseArray(template.getAppIds());
            data.put("app_ids", appIdsArray);
        }
        if (null != template.getProductPlatformId() && !"".equals(template.getProductPlatformId().trim())) {
            data.put("product_platform_id", template.getProductPlatformId());
        }
        if (null != template.getExternalUrlParams() && !"".equals(template.getExternalUrlParams().trim())) {
            data.put("external_url_params", template.getExternalUrlParams());
        }
        if (null != template.getOpenUrlParams() && !"".equals(template.getOpenUrlParams().trim())) {
            data.put("open_url_params", template.getOpenUrlParams());
        }
        if (null != template.getDpaLocalAudience() && !"".equals(template.getDpaLocalAudience().trim())) {
            data.put("dpa_local_audience", Long.parseLong(template.getDpaLocalAudience()));
        }
        if (null != template.getExcludeCustomActions() && !"".equals(template.getExcludeCustomActions().trim())) {
            JSONArray excludeCustomActionsArray = JSONArray.parseArray(template.getExcludeCustomActions());
            data.put("exclude_custom_actions", excludeCustomActionsArray);
        }
        if (null != template.getIncludeCustomActions() && !"".equals(template.getIncludeCustomActions().trim())) {
            JSONArray includeCustomActionsArray = JSONArray.parseArray(template.getIncludeCustomActions());
            data.put("include_custom_actions", includeCustomActionsArray);
        }
        if (null != template.getSuperiorPopularityType() && !"".equals(template.getSuperiorPopularityType().trim())) {
            data.put("superior_popularity_type", template.getSuperiorPopularityType());
        }
        if (null != template.getFlowPackage() && !"".equals(template.getFlowPackage().trim())) {
            JSONArray flowPackageArray = JSONArray.parseArray(template.getFlowPackage());
            data.put("flow_package", flowPackageArray);
        }
        if (null != template.getExcludeFlowPackage() && !"".equals(template.getExcludeFlowPackage().trim())) {
            JSONArray excludeFlowPackageArray = JSONArray.parseArray(template.getExcludeFlowPackage());
            data.put("exclude_flow_package", excludeFlowPackageArray);
        }
        if (null != template.getAutoExtendEnabled() && !"".equals(template.getAutoExtendEnabled().trim())) {
            data.put("auto_extend_enabled", template.getAutoExtendEnabled());
        }
        return data;
    }

    @Override
    public Map<String, Object> getAdvertiserCampaignList(String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_get");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("page", 1);
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.error("获取广告组信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", code);
            resultMap.put("message", jsonObject.getString("message"));
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.info("获取广告组信息为空==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", code);
            resultMap.put("message", "获取广告组信息为空");
            return resultMap;
        }
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        resultMap.put("data", data);
        return resultMap;
    }

    /**
     * 获取流量包数据接口
     *
     * @param accountId
     * @return
     */
    @Override
    public Map<String, Object> flowPackageGet(String accountId) {
        JSONObject jsonObject = flowPackageGetJsonObject(accountId);
        JSONObject result = new JSONObject();
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        result.put("code", code);
        result.put("message", message);
        if (null == code || code != 0) {
            result.put("success", false);
            return result;
        }
        JSONArray packageList = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null != packageList && packageList.size() > 0) {
            JSONArray packageArray = new JSONArray();
            for (int i = 0; i < packageList.size(); i++) {
                JSONObject packageObject = packageList.getJSONObject(i);
                packageObject.remove("rit");
                String status = packageObject.getString("status");
                if (null != status && "FLOW_PACKAGE_ENABLE".equals(status)) {
                    packageArray.add(packageObject);
                }
            }
            result.put("data", packageArray);
        }
        result.put("success", true);
        return result;
    }

    @Override
    public void getMaterialList(CtopOauthToken token) {
        getAdImageByPage(token, "", 1);
        getVideoByPage(token, "", 1);
    }

    private void getVideoByPage(CtopOauthToken token, String videoIds, int page) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/file/video/get/";
        // 请求参数
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page", page);
        param.put("page_size", 100);
        if (null != videoIds && !"".equals(videoIds.trim())) {
            String[] getIds = videoIds.split(StringUtils.COMMA);
            if (null != getIds && getIds.length > 0) {
                JSONObject filter = new JSONObject();
                JSONArray idArray = new JSONArray();
                for (int i = 0; i < getIds.length; i++) {
                    idArray.add(getIds[i]);
                }
                filter.put("video_ids", idArray);
                param.put("filtering", filter);
            }
        }

        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
        Integer code = resultObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.error("获取视频素材库接口异常==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        JSONArray data = resultObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.info("获取视频素材信息不存在==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceVideoInfo videoInfo = new ByteDanceVideoInfo(dataObject, token);
            videoInfoService.saveOrUpdate(videoInfo);
        }
        getVideoByPage(token, videoIds, page + 1);
    }


    public void getAdImageByPage(CtopOauthToken token, String imageIds, int page) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/file/image/ad/get/";
        // 请求参数
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page", page);
        param.put("page_size", 100);
        if (null != imageIds && !"".equals(imageIds.trim())) {
            String[] getIds = imageIds.split(StringUtils.COMMA);
            if (null != getIds && getIds.length > 0) {
                JSONArray idArray = new JSONArray();
                for (int i = 0; i < getIds.length; i++) {
                    idArray.add(getIds[i]);
                }
                param.put("image_ids", idArray);
            }
        }

        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
        Integer code = resultObject.getInteger("code");
        if (null == code || !code.equals(0)) {
            log.error("获取图片素材库接口异常==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        JSONArray data = resultObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.info("获取图片素材信息不存在==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceImageInfo imageInfo = new ByteDanceImageInfo(dataObject, token);
            imageInfoService.saveOrUpdate(imageInfo);
        }
        getAdImageByPage(token, imageIds, page + 1);
    }


    public JSONObject flowPackageGetJsonObject(String accountId) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/tools/union/flow_package/get/";
        // 请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("page", 1);
        params.put("page_size", 100);
        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
        return resultObject;
    }




    private void getAdvertiserCampaignByPageNumber(String accountId, Integer pageNumber, String ids, String date) {
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_get");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        JSONObject filtering = new JSONObject();
        if (null != ids && !"".equals(ids.trim())) {
            String[] idsArray = ids.split(StringUtils.COMMA);
            JSONArray filterIdsArray = new JSONArray();
            for (int i = 0; i < idsArray.length; i++) {
                Long id = Long.parseLong(idsArray[i]);
                filterIdsArray.add(id);
            }
            filtering.put("ids", filterIdsArray);
        }
        if (null != date && !"".equals(date)) {
            filtering.put("campaign_create_time", date);
        }
        params.put("filtering", filtering.toJSONString());
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("page", pageNumber + "");
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.error("获取广告组信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            return;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.error("获取广告组信息不存在==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCampaign campaign = new ByteDanceCampaign(dataObject, accountId);
            campaignService.saveOrUpdate(campaign);
        }
        getAdvertiserCampaignByPageNumber(accountId, pageNumber + 1, ids, date);
    }
}
