package com.xxl.job.executor.material.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.common.service.ICtopOauthTokenService;
import com.xxl.job.executor.material.entity.*;
import com.xxl.job.executor.material.mapper.ByteDanceCreativeMapper;
import com.xxl.job.executor.material.service.*;
import com.xxl.job.executor.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author 宋英豪
 */
@Slf4j
@Service
@Primary
public class ByteDanceAdvertiserDataServiceImpl implements IByteDanceAdvertiserDataService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceAdvertisePlanService advertisePlanService;
    @Autowired
    private IByteDanceCreativeMaterialService creativeMaterialService;
    @Autowired
    private ByteDanceCreativeMapper creativeMapper;
    @Autowired
    private IByteDanceVideoInfoService videoInfoService;

    @Override
    public JSONObject getAdvertiserList(String token, Long accountId) {
        JSONObject returnJson = new JSONObject();
        try {
            String url = "https://ad.oceanengine.com/open_api/2/majordomo/advertiser/select/";
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("advertiser_id", accountId);
            String result = HttpUtils.httpGetRequest(url, headers, params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            System.err.println(jsonObject);
            if (Check.isNull(jsonObject)) {
                throw new Exception("返回结果为空");
            }

            int code = jsonObject.getInteger("code");
            if (code == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (Check.isNull(data)) {
                    throw new Exception("data为空");
                }
                JSONArray list = data.getJSONArray("list");
                if (Check.isNull(list)) {
                    throw new Exception("账户列表为空");

                }
                returnJson.put("code", 0);
                returnJson.put("data", list);

            } else {
                returnJson.put("code", -1);
            }


        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);

        }


        return returnJson;


    }

    @Override
    public Map<String, Object> getAdvertiserInfo(String accountId, String token) {
        Map<String, Object> resultMap = new HashMap<>();
        //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", token);
        TreeMap<String, Object> params = new TreeMap<>();
        //TODO jsonArray
        params.put("advertiser_ids", "[" + accountId + "]");
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        int code = jsonObject.getInteger("code");

        if (code != 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;
    }


    @Override
    public JSONArray advertiserList(String token) {
        String url = "https://ad.oceanengine.com/open_api/oauth2/advertiser/get/";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("access_token", token);
        String appId = PropertiesUtils.getValue("bytedance_config", "bytedance_appid");
        String secret = PropertiesUtils.getValue("bytedance_config", "bytedance_secret");
        params.put("secret", secret);
        params.put("app_id", appId);
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info("返回信息：{}", jsonObject);
        Integer code = jsonObject.getInteger("code");
        if (code == 0) {
            JSONObject dataJson = jsonObject.getJSONObject("data");
            if (!Check.isNull(dataJson)) {
                JSONArray listArr = dataJson.getJSONArray("list");
                if (!Check.isNull(listArr)) {
                    return listArr;
                }
            }
        }
        return new JSONArray();
    }

    @Override
    public ByteDanceAdvertisePlan getSinglePlanById(CtopOauthToken token, String id){
        JSONArray getIds = new JSONArray();
        getIds.add(id);
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_get");
        // 请求参数
        Map<String, Object> filtering = new HashMap<>();
        filtering.put("ids", getIds);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page", 1);
        param.put("page_size", 100);
        param.put("filtering", filtering);
        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 null;
        }
        JSONArray data = resultObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            return null;
        }
        JSONObject dataObject = data.getJSONObject(0);
        ByteDanceAdvertisePlan advertisePlan = new ByteDanceAdvertisePlan(dataObject, String.valueOf(token.getAccountId()));
        BigDecimal deepCpabid = dataObject.getBigDecimal("deep_cpabid");
        if (null != deepCpabid) {
            advertisePlan.setDeepCpaBid(deepCpabid);
        }
        return advertisePlan;
    }


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

        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_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);
        }
        if (null != updateDate && !"".equals(updateDate)) {
            filtering.put("ad_modify_time", updateDate);
        }

        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page", pageNum);
        param.put("page_size", 100);
        param.put("filtering", filtering);
        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.isEmpty()) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceAdvertisePlan advertisePlan = new ByteDanceAdvertisePlan(dataObject, String.valueOf(token.getAccountId()));
            BigDecimal deepCpabid = dataObject.getBigDecimal("deep_cpabid");
            if (null != deepCpabid) {
                advertisePlan.setDeepCpaBid(deepCpabid);
            }
            advertisePlanService.saveOrUpdate(advertisePlan);
        }
        getAd(token, pageNum + 1, ids, date, updateDate);
    }

    @Override
    public Map<String, Object> getAdvertiserPlan(CtopOauthToken token, String ids, String date, String updateDate) {
        Map<String, Object> resultMap = new HashMap<>();
        getAd(token, 1, ids, date, updateDate);
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告计划信息成功");
        XxlJobHelper.log("头条计划数据获取完成:accountId=>{}",token.getAccountId());
        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.error("获取广告预算信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "获取广告预算信息接口异常");
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.isEmpty()) {
            log.info("广告主预算信息不存在==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", 0);
            resultMap.put("message", "获取广告主预算信息完成");
            return resultMap;
        }
        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.error("获取广告主创意素材信息接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "获取广告主创意素材信息接口异常");
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONArray("data");
        if (null == data || data.isEmpty()) {
            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;
    }


    private void getCreativeByPage(CtopOauthToken token, String date, int pageNum) {
        JSONObject resultObject = getCreative(token, date, pageNum);
        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.isEmpty()) {
            return;
        }
        List<ByteDanceCreative> creatives = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCreative creative = new ByteDanceCreative(dataObject, token);
            creatives.add(creative);
        }
        creativeMapper.replaceBatch(creatives);
        getVideoByPage(token, date, pageNum + 1);
    }


    public JSONObject getCreative(CtopOauthToken token, String date, int pageNumber) {
        final Long advertiser_id = token.getAccountId();  //操作的广告主id
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/creative/get/";

        // 请求参数
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiser_id);
        param.put("page", pageNumber);
        param.put("page_size", 100);
        if (null != date && !"".equals(date.trim())) {
            JSONObject filtering = new JSONObject();
            filtering.put("creative_modify_time", date);
            param.put("filtering", filtering);
        }
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
    }

    @Override
    public Map<String, Object> advertiserPlanUpdateStatus(CtopOauthToken token, String adIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray ids = new JSONArray();
        String[] getIds = adIds.split(StringUtils.COMMA);
        if (getIds.length > 0) {
            for (String getId : getIds) {
                ids.add(Long.parseLong(getId));
            }
        }
        //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", token.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("ad_ids", ids.toJSONString());
        params.put("opt_status", optStatus);
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        int code = jsonObject.getInteger("code");
        if (code != 0) {
            log.error("广告计划更新状态接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告计划更新状态接口异常");
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告计划更新状态异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告计划更新状态异常");
            return resultMap;
        }
        JSONArray getAdIds = data.getJSONArray("ad_ids");
        if (null != getAdIds && !getAdIds.isEmpty()) {
            //获取广告计划信息
            getAdvertiserPlan(token, adIds, null, null);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "广告组状态修改成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> advertiserPlanUpdateBid(CtopOauthToken token, String adIds, String bids) {
        Map<String, Object> resultMap = new HashMap<>();
        String[] getadIds = adIds.split(StringUtils.COMMA);
        String[] getBids = bids.split(StringUtils.COMMA);
        JSONArray data = new JSONArray();
        if (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);
            }
        }
        //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", token.getAccessToken());

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

    @Override
    public Map<String, Object> advertiserPlanUpdateBudget(CtopOauthToken token, 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 (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);
            }
        }
        //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", token.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.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:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划预算接口异常");
            return resultMap;
        }
        JSONObject getData = jsonObject.getJSONObject("data");
        if (null == getData) {
            log.info("修改计划预算异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改计划预算异常");
            return resultMap;
        }
        JSONArray getAdIds = getData.getJSONArray("ad_ids");
        if (null != getAdIds && !getAdIds.isEmpty()) {
            //获取广告计划信息
            getAdvertiserPlan(token, adIds, null, 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<>();
        if (null == accountId || "".equals(accountId.trim())) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_PARAM_ERROR);
            return resultMap;
        }
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        if (null == token) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_PARAM_ERROR);
            return resultMap;
        }
        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");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("获取人群包信息接口异常==》accountId:{},message:{}", accountId, message);
            resultMap.put("success", false);
            resultMap.put("message", message);
            resultMap.put("code", -1);
            return resultMap;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("custom_audience_list");
        if (null == data || data.isEmpty()) {
            log.info("人群包信息不存在==》accountId:{},message:{}", accountId, 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> 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.isEmpty()) {
            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.isEmpty()) {
            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 ("FLOW_PACKAGE_ENABLE".equals(status)) {
                    packageArray.add(packageObject);
                }
            }
            result.put("data", packageArray);
        }
        result.put("success", true);
        return result;
    }

    @Override
    public void getMaterialList(CtopOauthToken token) {
        getVideoByPage(token, "", 1);
        getImageByPage(token, "", 1);
        videoInfoService.updateMaterialType();
        imageInfoService.updateType();
    }

    @Autowired
    private IBytedanceImageInfoService imageInfoService;

    @Override
    public void getImageByPage(CtopOauthToken token, String imageIds, int page) {
        // 请求地址
        String url = "https://ad.oceanengine.com/open_api/2/file/image/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 (getIds.length > 0) {
                JSONObject filter = new JSONObject();
                JSONArray idArray = new JSONArray();
                Collections.addAll(idArray, getIds);
                filter.put("image_ids", idArray);
                param.put("filtering", filter);
            }
        }

        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
        if (null == resultObject) {
            log.error("获取图片素材库接口异常==》accountId:{}", token.getAccountId());
            return;
        }
        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.isEmpty()) {
            log.info("获取图片素材完成==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        List<BytedanceImageInfo> videoInfoList = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            BytedanceImageInfo imageInfo = new BytedanceImageInfo(dataObject, token);
            videoInfoList.add(imageInfo);
        }
        imageInfoService.replaceBatch(videoInfoList);
        getImageByPage(token, imageIds, page + 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 (getIds.length > 0) {
                JSONObject filter = new JSONObject();
                JSONArray idArray = new JSONArray();
                Collections.addAll(idArray, getIds);
                filter.put("video_ids", idArray);
                param.put("filtering", filter);
            }
        }

        JSONObject resultObject = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, param);
        if (null == resultObject) {
            log.error("获取视频素材库接口异常==》accountId:{}", token.getAccountId());
            return;
        }
        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.isEmpty()) {
            log.info("获取视频素材完成==》accountId:{},message:{}", token.getAccountId(), resultObject.getString("message"));
            return;
        }
        List<ByteDanceVideoInfo> videoInfoList = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceVideoInfo videoInfo = new ByteDanceVideoInfo(dataObject, token);
            videoInfoList.add(videoInfo);
        }
        videoInfoService.replaceBatch(videoInfoList);
        getVideoByPage(token, videoIds, 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);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
    }


    @Override
    public void getBytedancePlanList(String accountId, String accessToken, int pageNum, String createDate, String updateDate) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_get");
        // 请求参数
        Map<String, Object> filtering = new HashMap<>();
        if (null != createDate && !"".equals(createDate)) {
            filtering.put("ad_create_time", createDate);
        }
        if (null != updateDate && !"".equals(updateDate)) {
            filtering.put("ad_modify_time", updateDate);
        }

        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("page", pageNum);
        param.put("page_size", 1000);
        param.put("filtering", filtering);
        JSONObject resultObject = HttpUtils.bytedanceGetRequest(accessToken, url, param);
        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.isEmpty()) {
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceAdvertisePlan advertisePlan = new ByteDanceAdvertisePlan(dataObject, accountId);
            BigDecimal deepCpabid = dataObject.getBigDecimal("deep_cpabid");
            if (null != deepCpabid) {
                advertisePlan.setDeepCpaBid(deepCpabid);
            }
            //   advertisePlanService.saveOrUpdate(advertisePlan);
        }
        getBytedancePlanList(accountId, accessToken, pageNum + 1, createDate, updateDate);
    }


}
