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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.OauthConfig;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.enums.MaterialEnum;
import cn.com.ctop.common.module.mapper.KuaiShouOcpxActionTypeConfigMapper;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.service.IMessageTemplate;
import cn.com.ctop.common.module.service.IOauthConfigService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.JsonUtil;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.service.IAiCreativeLimitService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAccountCreativeOverrunInfoService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationGroupService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouAdvertiserBaseInfo;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouAppList;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCampaign;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouDailyFlows;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouRegionListChildren;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouRegionListParent;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouTargetingTags;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouPopulation;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.ConvertVo;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouAdvertiserBaseInfoMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouAppListMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouRegionListChildrenMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouRegionListParentMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouTargetingTagsMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCampaignService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCreativeService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouDailyFlowsService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouHistoryReportTaskService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouOverRunSendMessageService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouPopulationService;
import cn.com.ctop.kuaishou.modules.batch.service.IWarningOperationService;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResult;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResultToken;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAccount;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyCampaign;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyCreative;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyCreativeStatistic;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportHourlyAccount;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportHourlyCampaign;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportHourlyCreative;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportHourlyCreativeStatistic;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportHourlyGroup;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyAccountMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyCampaignMapper;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyCampaignService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyCreativeService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportHourlyAccountService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportHourlyCampaignService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportHourlyCreativeService;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportHourlyGroupService;
import cn.com.ctop.kuaishou.modules.report.service.IRuleKuaiShouPlanService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.ParseException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author
 */
@Slf4j
@Service
public class KuaishouInterfaceServiceImpl implements IKuaishouInterfaceService {

    @Autowired
    KuaishouReportDailyCampaignMapper dailyCampaignMapper;
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private KuaiShouRegionListChildrenMapper regionListChildrenMapper;
    @Autowired
    private KuaiShouRegionListParentMapper regionListParentMapper;
    @Autowired
    private KuaiShouAppListMapper appListMapper;
    @Autowired
    private IKuaishouReportHourlyAccountService hourlyAccountService;
    @Autowired
    private KuaiShouAdvertiserBaseInfoMapper advertiserBaseInfoMapper;
    @Autowired
    private IKuaiShouImageGetService iKuaiShouImageGetService;
    @Autowired
    private KuaiShouTargetingTagsMapper targetingTagsMapper;
    @Autowired
    private KuaishouReportDailyAccountMapper dailyAccountMapper;
    @Autowired
    private IKuaishouReportHourlyCampaignService hourlyCampaignService;
    @Autowired
    private IKuaishouReportDailyCampaignService dailyCampaignService;
    @Autowired
    private IKuaishouReportHourlyGroupService hourlyGroupService;
    @Autowired
    private IKuaishouReportDailyCreativeService dailyCreativeService;
    @Autowired
    private IKuaishouReportHourlyCreativeService hourlyCreativeService;
    @Autowired
    private IKuaiShouVideoGetService kuaiShouVideoGetService;
    @Autowired
    private IKuaiShouCreativeService kuaiShouCreativeService;
    @Autowired
    private IKuaiShouCampaignService kuaiShouCampaignService;
    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private IKuaiShouHistoryReportTaskService historyReportTaskService;
    @Autowired
    private IKuaiShouImageGetService kuaiShouImageGetService;
    @Autowired
    private IKuaiShouDailyFlowsService kuaiShouDailyFlowsService;
    @Autowired
    private IKuaishouPopulationService populationService;
    @Autowired
    private IKuaiShouGroupService getKuaiShouGroupService;
    @Autowired
    private IWarningOperationService warningOperationService;

    @Autowired
    private IKuaishouDirectionalPackageService directionalPackageService;
    @Autowired
    private IKuaishouPopulationGroupService populationGroupService;
    @Autowired
    private IKuaishouAppPackageService appPackageService;
    @Autowired
    private UserAllocationMapper allocationMapper;
    @Autowired
    private KuaiShouOcpxActionTypeConfigMapper ocpxActionTypeConfigMapper;
    @Autowired
    private IMessageTemplate messageTemplate;
    @Autowired
    private RedisUtil redisUtil;
    private static ExecutorService cutExecutorService = Executors.newFixedThreadPool(10);

    @Value("${kuaishou.realuser-ip}")
    private String realUserIP;

    @Override
    public void getAdvertiserReportHourly(CtopOauthToken token, Date startDate, Date endDate) {
        try {
            Thread.sleep(200L);
            getAdvertiserReportHourlyByPage(token, startDate, endDate, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void getAdvertiserReportHourlyByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ACCOUNT_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", DateUtils.formatDate(startDate));
        param.put("end_date", DateUtils.formatDate(endDate));
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", 2000);
        param.put("page", page);
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告主时报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.error("快手时报返回详情为空，accountId：{}", token.getAccountId());
            return;
        }
        List<KuaishouReportHourlyAccount> addList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            KuaishouReportHourlyAccount kuaishouReportHourlyAccount = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyAccount.class);
            kuaishouReportHourlyAccount.setAccountId(token.getAccountId());
            kuaishouReportHourlyAccount.setId("" + token.getAccountId() + kuaishouReportHourlyAccount.getStatDate() + kuaishouReportHourlyAccount.getStatHour());
            //  hourlyAccountService.saveOrUpdate(kuaishouReportHourlyAccount);
            addList.add(kuaishouReportHourlyAccount);
        }
        hourlyAccountService.replaceBatch(addList);
        log.info("获取账户时报数据完成，accountId：{}", token.getAccountId());
    }


    @Override
    public void getVideoList(CtopOauthToken token, String startDate, String endDate) {
        getVideoListByPage(token, startDate, endDate, 1);
    }


    private void getVideoListByPage(CtopOauthToken token, String startDate, String endDate, int page) {
        try {
            //  log.info("获取视频数据，accountId：{}", token.getAccountId());
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token.getAccessToken());
            Map<String, Object> param = new HashMap<>();
            param.put("advertiser_id", token.getAccountId());
            Integer page_size = 500;
            param.put("page_size", page_size);
            param.put("page", page);
            if (!Check.isNull(startDate) && !Check.isNull(endDate)) {
                param.put("start_date", startDate);
                param.put("end_date", endDate);
            }
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (Check.isNull(resultJson)) {
                return;
            }
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            if (null == code || code != 0) {
                log.error("获取快手视频列表数据异常:{},accountId:{}", message, token.getAccountId());
                return;
            }
            JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
            if (null == details || details.size() <= 0) {
                log.info("快手视频列表信息为空=》accountId:{}", token.getAccountId());
                return;
            }
            Boolean toGet = false;
            if (details.size() >= page_size) {
                toGet = true;
            }

            List<KuaiShouVideoGet> videoGetList = new ArrayList<>();
            for (int i = 0; i < details.size(); i++) {
                JSONObject detailJson = details.getJSONObject(i);
                if (Check.isNull(detailJson)) {
                    continue;
                }
                KuaiShouVideoGet videoGet = new KuaiShouVideoGet();
                String photo_id = detailJson.getString("photo_id");
                videoGet.setId(token.getAccountId() + photo_id);
                videoGet.setAccountId(token.getAccountId());
                videoGet.setCoverUrl(detailJson.getString("cover_url"));
                videoGet.setPhotoId(photo_id);
                videoGet.setPhotoName(detailJson.getString("photo_name"));
                videoGet.setStatDate(detailJson.getDate("upload_time"));
                String signature = detailJson.getString("signature");
                videoGet.setSignature(signature);
                Integer source = detailJson.getInteger("source");
                if (source == 2) {
                    videoGet.setChannelType(1);
                } else {
                    videoGet.setChannelType(0);
                }
                Integer new_status = detailJson.getInteger("new_status");
                if (new_status == 1) {
                    videoGet.setStatus(0);
                } else {
                    videoGet.setStatus(1);
                }
                videoGet.setUrl(detailJson.getString("url"));
                Integer width = detailJson.getInteger("width");
                videoGet.setWidth(width);
                Integer height = detailJson.getInteger("height");
                videoGet.setHeight(height);
                Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(width, height);
                if (!Check.isNullMap(typeBySize)) {
                    videoGet.setMaterialType(typeBySize.get("type"));
                    videoGet.setIsKaiPing(typeBySize.get("isKaiPing"));
                }
                videoGetList.add(videoGet);
                getCut(token.getAccessToken(), token.getAccountId(), signature, photo_id);
            }
            if (!Check.isNull(videoGetList)) {
                videoGetService.replaceBatch(videoGetList);
            }

            if (toGet) {
                getVideoListByPage(token, startDate, endDate, page + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void getCut(String token, Long accountId, String signature, String photo_id) {
        cutExecutorService.submit(new Runnable() {
            @Override
            public void run() {
                videoGetService.getKeyFrame(token, accountId, signature, photo_id);
            }
        });

    }


    @Override
    public void getAdvertiserReportDaily(CtopOauthToken token, Date startDate, Date endDate, String reportDims) {
        try {
            Thread.sleep(400L);
            getAccountDailyReportByPage(token, startDate, endDate, 1, reportDims);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void getAccountDailyReportByPage(CtopOauthToken token, Date startDate, Date endDate, int page, String reportDims) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ACCOUNT_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        if (!Check.isNull(startDate)) {
            param.put("start_date", DateUtils.formatDate(startDate));
        }

        if (!Check.isNull(endDate)) {
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        if (!Check.isNull(reportDims)) {
            JSONArray array = new JSONArray();
            array.add(reportDims);
            param.put("report_dims", array);
        }

        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", 2000);
        param.put("page", page);
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告主报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告主报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportDailyAccount> addList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            if (!Check.isNull(detailJson)) {
                detailJson.put("photo_share", detailJson.getString("share"));
                detailJson.put("photo_comment", detailJson.getString("comment"));
                detailJson.put("photo_like", detailJson.getString("like"));
                detailJson.put("photo_show", detailJson.getString("show"));
                KuaishouReportDailyAccount KuaishouReportDailyAccount = JSONObject.toJavaObject(detailJson, KuaishouReportDailyAccount.class);
                KuaishouReportDailyAccount.setAccountId(token.getAccountId());
                addList.add(KuaishouReportDailyAccount);
            }
        }
        if (Check.isNull(reportDims)) {
            dailyAccountMapper.replaceBatch(addList);
        } else {
            dailyAccountMapper.replaceBatchAdScene(addList);
        }
        getAccountDailyReportByPage(token, startDate, endDate, page + 1, reportDims);
    }

    @Override
    public void getAdvertiserCampaignReportDaily(CtopOauthToken token, Date startDate, Date endDate) {
        getCampaignDailyReportByPage(token, startDate, endDate, 1);
    }

    private void getCampaignDailyReportByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();

        if (!Check.isNull(startDate)) {
            param.put("start_date", DateUtils.formatDate(startDate));
        }
        if (!Check.isNull(endDate)) {
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", 500);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告计划报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告计划报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }

        List<KuaishouReportDailyCampaign> campaigns = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            var detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var campaign = JSONObject.toJavaObject(detailJson, KuaishouReportDailyCampaign.class);
            campaign.setAccountId(token.getAccountId());
            campaigns.add(campaign);
        }
        if (!campaigns.isEmpty()) {
            dailyCampaignService.replaceBatch(campaigns);
        }
        getCampaignDailyReportByPage(token, startDate, endDate, page + 1);
    }

    @Override
    public KuaishouResult<KuaishouReportDailyCampaign> getCampaignDailyReport(String accessToken, Long advertiserId, String startDate, String endDate, int pageSize, int pageNum) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", advertiserId);
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportDailyCampaign> kuaishouResult = null;
        try {
            String result = HttpUtils.httpPostRequest(url, param, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaishouResult = mapper.readValue(result, new TypeReference<KuaishouResult<KuaishouReportDailyCampaign>>() {
            });
            List<KuaishouReportDailyCampaign> details = kuaishouResult.getData().getDetails();
            details.forEach((campaign) -> {
                campaign.setAccountId(advertiserId);
                dailyCampaignService.saveOrUpdate(campaign);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }

    @Override
    public void getAdvertiserCampaignReportHourly(CtopOauthToken token, Date startDate, Date endDate) {
        getCampaignReportHourlyByPage(token, startDate, endDate, 1);
    }

    private void getCampaignReportHourlyByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", DateUtils.formatDate(startDate));
        param.put("end_date", DateUtils.formatDate(endDate));
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", 2000);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告计划时报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告计划时报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportHourlyCampaign> campaigns = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var hourlyCampaign = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyCampaign.class);
            hourlyCampaign.setAccountId(token.getAccountId());
            hourlyCampaign.setId("" + hourlyCampaign.getAccountId() + hourlyCampaign.getCampaignId() + hourlyCampaign.getStatDate() + hourlyCampaign.getStatHour());
            hourlyCampaign.setCreateTime(new Date());
            hourlyCampaign.setUpdateTime(new Date());
            campaigns.add(hourlyCampaign);
        }
        hourlyCampaignService.replaceBatch(campaigns);
        getCampaignReportHourlyByPage(token, startDate, endDate, page + 1);
    }


    @Override
    public KuaishouResult<KuaishouReportHourlyCampaign> getCampaignHourlyReport(String accessToken, Long advertiserId, String startDate, String endDate, int pageSize, int pageNum) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", advertiserId);
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportHourlyCampaign> kuaishouResult = null;
        try {
            String result = HttpUtils.httpPostRequest(url, param, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaishouResult = mapper.readValue(result, new TypeReference<KuaishouResult<KuaishouReportHourlyCampaign>>() {
            });
            List<KuaishouReportHourlyCampaign> campaigns = kuaishouResult.getData().getDetails();
            campaigns.forEach((campaign) -> {
                campaign.setAccountId(advertiserId);
                campaign.setId("" + campaign.getAccountId() + campaign.getCampaignId() + campaign.getStatDate() + campaign.getStatHour());
                hourlyCampaignService.saveOrUpdate(campaign);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }


    @Override
    public KuaishouResult<KuaishouReportHourlyGroup> getGroupHourlyReport(String accessToken, Long advertiserId, String startDate, String endDate, int pageSize, int pageNum) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GTOUP_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", advertiserId);
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportHourlyGroup> kuaishouResult = null;
        try {
            String result = HttpUtils.httpPostRequest(url, param, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaishouResult = mapper.readValue(result, new TypeReference<KuaishouResult<KuaishouReportHourlyGroup>>() {
            });
            List<KuaishouReportHourlyGroup> hourlyGroups = kuaishouResult.getData().getDetails();
            hourlyGroups.forEach((hourlyGroup) -> {
                hourlyGroup.setAccountId(advertiserId);
                hourlyGroup.setId("" + hourlyGroup.getAccountId() + hourlyGroup.getUnitId() + hourlyGroup.getStatDate() + hourlyGroup.getStatHour());
                hourlyGroupService.saveOrUpdate(hourlyGroup);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }

    @Override
    public void getAdvertiserCreativeReportDaily(CtopOauthToken token, Date startDate, Date endDate, JSONArray campaignIds, JSONArray creativeIds) {
        getAdvertiserCreativeReportDailyByPage(token, startDate, endDate, campaignIds, creativeIds, 1);
    }

    private void getAdvertiserCreativeReportDailyByPage(CtopOauthToken token, Date startDate, Date endDate, JSONArray campaignIds, JSONArray creativeIds, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_REPORT;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<String, Object>();
        if (!Check.isNull(startDate)) {
            param.put("start_date", DateUtils.formatDate(startDate));
        }
        if (!Check.isNull(endDate)) {
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        if (!Check.isNull(campaignIds) && campaignIds.size() > 0) {
            param.put("campaign_ids", campaignIds);

        }
        if (!Check.isNull(creativeIds) && creativeIds.size() > 0) {
            param.put("creative_ids", creativeIds);

        }
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", 1000);
        param.put("page", page);


        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告创意分天报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告创意分天报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        for (int i = 0; i < details.size(); i++) {
            var detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var creative = JSONObject.toJavaObject(detailJson, KuaishouReportDailyCreative.class);
            creative.setAccountId(token.getAccountId());
            // 取得MD5
         /*   String signature = creativeService.getCodeByCreativeId(creative.getCreativeId());
            if (!Check.isNull(signature)) {
                creative.setSignature(signature);
            }*/
            dailyCreativeService.saveOrUpdate(creative);
        }
        getAdvertiserCreativeReportDailyByPage(token, startDate, endDate, campaignIds, creativeIds, page + 1);
    }

    private KuaishouReportDailyCreativeStatistic setDailyStatistic(KuaishouReportDailyCreative creative, CtopOauthToken token) {
        KuaishouReportDailyCreativeStatistic statistic = new KuaishouReportDailyCreativeStatistic(creative);
        KuaiShouCreative getCreative = kuaiShouCreativeService.getById("" + token.getAccountId() + creative.getCreativeId());
        if (null != getCreative) {
            statistic.setCreativeName(getCreative.getCreativeName());
            KuaiShouCampaign getCampaign = kuaiShouCampaignService.getById("" + token.getAccountId() + getCreative.getCampaignId());
            if (null != getCampaign) {
                statistic.setCampaignId(getCampaign.getCampaignId());
                statistic.setCampaignName(getCampaign.getCampaignName());
            }
            KuaiShouGroup getGroup = kuaiShouGroupService.getById("" + token.getAccountId() + getCreative.getUnitId());
            if (null != getGroup) {
                statistic.setUnitId(getGroup.getUnitId());
                statistic.setUnitName(getGroup.getUnitName());
            }
            KuaiShouVideoGet getVideo = kuaiShouVideoGetService.getById("" + token.getAccountId() + getCreative.getPhotoId());
            if (null != getVideo) {
                statistic.setSignature(getVideo.getSignature());
                statistic.setUrl(getVideo.getUrl());
            }
            UserAllocation allocation = userAllocationService.getByAccountId(token.getAccountId());
            if (null != allocation) {
                statistic.setAccountName(allocation.getAuthName());
            }
        }
        return statistic;
    }

    @Override
    public KuaishouResult<KuaishouReportDailyCreative> getCreativeDailyReport(String accessToken, Long advertiserId, String startDate, String endDate, int pageSize, int pageNum) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_REPORT;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", advertiserId);
        param.put("temporal_granularity", "DAILY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportDailyCreative> kuaishouResult = null;
        try {
            String result = HttpUtils.httpPostRequest(url, param, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaishouResult = mapper.readValue(result, new TypeReference<KuaishouResult<KuaishouReportDailyCreative>>() {
            });
            List<KuaishouReportDailyCreative> dailyCreatives = kuaishouResult.getData().getDetails();
            dailyCreatives.forEach((creative) -> {
                creative.setAccountId(advertiserId);
                dailyCreativeService.saveOrUpdate(creative);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }

    @Override
    public void getAdvertiserCreativeReportHourly(CtopOauthToken token, Date startDate, Date endDate) {
        getAdvertiserCreativeReportHourlyByPage(token, startDate, endDate, 1);
    }


    private void getAdvertiserCreativeReportHourlyByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_REPORT;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());
        Map<String, Object> param = new HashMap<>();
        param.put("start_date", DateUtils.formatDate(startDate));
        param.put("end_date", DateUtils.formatDate(endDate));
        param.put("advertiser_id", token.getAccountId());
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", 2000);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手广告创意时报表异常:{},accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            log.info("快手广告创意时报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportHourlyCreative> creatives = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var creative = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyCreative.class);
            creative.setAccountId(token.getAccountId());
            creative.setId("" + creative.getAccountId() + creative.getCreativeId() + creative.getStatDate() + creative.getStatHour());
            creative.setCreateTime(new Date());
            creative.setUpdateTime(new Date());
            creatives.add(creative);
        }
        hourlyCreativeService.replaceBatch(creatives);
        getAdvertiserCreativeReportHourlyByPage(token, startDate, endDate, page + 1);
    }


    private KuaishouReportHourlyCreativeStatistic setHourlyStatistic(KuaishouReportHourlyCreative creative, CtopOauthToken token) {
        KuaishouReportHourlyCreativeStatistic statistic = new KuaishouReportHourlyCreativeStatistic(creative);
        KuaiShouCreative getCreative = kuaiShouCreativeService.getById("" + token.getAccountId() + creative.getCreativeId());
        if (null != getCreative) {
            statistic.setCreativeName(getCreative.getCreativeName());
            KuaiShouCampaign getCampaign = kuaiShouCampaignService.getById("" + token.getAccountId() + getCreative.getCampaignId());
            if (null != getCampaign) {
                statistic.setCampaignId(getCampaign.getCampaignId());
                statistic.setCampaignName(getCampaign.getCampaignName());
            }
            KuaiShouGroup getGroup = kuaiShouGroupService.getById("" + token.getAccountId() + getCreative.getUnitId());
            if (null != getGroup) {
                statistic.setUnitId(getGroup.getUnitId());
                statistic.setUnitName(getGroup.getUnitName());
            }
            KuaiShouVideoGet getVideo = kuaiShouVideoGetService.getById("" + token.getAccountId() + getCreative.getPhotoId());
            if (null != getVideo) {
                statistic.setSignature(getVideo.getSignature());
                statistic.setUrl(getVideo.getUrl());
            }
            UserAllocation allocation = userAllocationService.getByAccountId(token.getAccountId());
            if (null != allocation) {
                statistic.setAccountName(allocation.getAuthName());
            }
        }
        return statistic;
    }

    @Override
    public KuaishouResult<KuaishouReportHourlyCreative> getCreativeHourlyReport(String accessToken, Long advertiserId, String startDate, String endDate, int pageSize, int pageNum) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_REPORT;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("start_date", startDate);
        param.put("end_date", endDate);
        param.put("advertiser_id", advertiserId);
        param.put("temporal_granularity", "HOURLY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportHourlyCreative> kuaishouResult = null;
        try {
            String result = HttpUtils.httpPostRequest(url, param, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaishouResult = mapper.readValue(result, new TypeReference<KuaishouResult<KuaishouReportHourlyCreative>>() {
            });
            List<KuaishouReportHourlyCreative> hourlyCreatives = kuaishouResult.getData().getDetails();
            hourlyCreatives.forEach((creative) -> {
                creative.setAccountId(advertiserId);
                creative.setId("" + creative.getAccountId() + creative.getCreativeId() + creative.getStatDate() + creative.getStatHour());
                hourlyCreativeService.saveOrUpdate(creative);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }


    @Override
    public void loadKuaishouDataSingle(CtopOauthToken token) throws java.text.ParseException {
        String beginDateStr = allocationMapper.getUserAllocation(token.getAccountId()).getAuthBeginTime();
        beginDateStr = Check.isNull(beginDateStr) ? DateUtils.formatDate(DateUtils.addDay(new Date(), -180), "yyyy-MM-dd") : beginDateStr;
        Date beginDate = DateUtils.parseDate(beginDateStr, DateUtils.WEB_FORMAT);
        Date endDate = DateUtils.addDay(new Date(), -1);
        while (!beginDate.after(endDate)) {
            beginDate = DateUtils.addDay(beginDate, 1);
            getAdvertiserReportHourly(token, beginDate, beginDate);
            getAdvertiserReportDaily(token, beginDate, beginDate, null);
        }
//        Date endDate = new Date();
//        for (int i = 0; i < 7; i++) {
//            Date getStartDate = DateUtils.addDay(endDate, -i);
        //1: 获取广告主信息数据
//            getAdvertiserReportHourly(token, beginDate, endDate);
//            getAdvertiserReportDaily(token, beginDate, endDate, null);
        //2：获取广告计划信息数据
        //getAdvertiserCampaignReportHourly(token, getStartDate, getStartDate);
        //3：获取广告组信息数据
        // getAdvertiserGroupReportHourly(token, getStartDate, getStartDate);
        //4: 获取广告创意信息数据
        // getAdvertiserCreativeReportHourly(token, getStartDate, getStartDate);
//        }
        //获取全量广告计划数据
        getCampaignList(token, null, null);
        //获取全量广组主数据
        getGroupList(token, null, null);
        //获取全量创意数据
        getCreativeList(token, null, null);
        getAppList(token.getAccountId(), token.getAccessToken());
        log.info("----------------开始历史数据获取，accountId：{}", token.getAccountId());
        String endDateStr = DateUtils.formatDate(endDate, "yyyy-MM-dd");
//        String startDate = DateUtils.addMonth(endDateStr, -1);
        historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), beginDateStr, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);
        getVideoList(token, null, null);
        //   getSuZaoList(token.getAccessToken(), token.getAccountId(), 1, null, null);
        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String videoEndDate = DateUtils.addDay(nowDate, -180);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date end = simpleDateFormat.parse(nowDate);
        Date start = simpleDateFormat.parse(videoEndDate);
        List<Date> dates = DateUtils.findDates(start, end);
        for (int i = 0; i < dates.size(); i++) {
            String formatDate = simpleDateFormat.format(dates.get(i));
            getImageList(token, formatDate);
        }


    }


    /**
     * 创建广告计划
     *
     * @param accessToken  token信息
     * @param advertiserId 广告主id
     * @param requestJson  请求参数拼装
     */
    @Override
    public Map<String, Object> campaignCreate(String accessToken, Long advertiserId, JSONObject requestJson) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_CREATE;
            Map<String, String> headers = new HashMap<>();

            headers.put("Access-Token", accessToken);
            headers.put("K-RealUser-IP", realUserIP);
            headers.put("Content-Type", " application/json");
            requestJson.put("advertiser_id", advertiserId);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    Long campaignId = dataJson.getLong("campaign_id");
                    returnMap.put("code", 0);
                    returnMap.put("message", "success");
                    returnMap.put("campaignId", campaignId);
                    returnMap.put("success", true);
                    // 创建成功 拉取广告组信息
                    Thread.sleep(100);
                    getCampaign(accessToken, advertiserId, campaignId);
                } else {
                    log.error("创建[广告计划]失败,账户ID:{},返回结果：{},------入参：{}", advertiserId, resultJson, requestJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创建广告计划失败");
                    returnMap.put("success", false);
                }
            } else {
                log.error("快手创建广告计划返回内容为空,advertiser_id:{}", advertiserId);
                returnMap.put("code", -1);
                returnMap.put("message", "创建广告计划错误");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建广告计划失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "创建广告计划失败");
            returnMap.put("desc", "Interface exception");
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 创建 广告组
     *
     * @param accessToken
     * @param advertiserId
     * @param requestJson
     * @return
     */
    @Override
    public Map<String, Object> adUnitCreate(String accessToken, Long advertiserId, JSONObject requestJson, Integer count) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("参数不能为空");
            }
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_UNIT_CREATE;
            Map<String, String> headers = new HashMap<>();
            requestJson.put("advertiser_id", advertiserId);
            headers.put("Access-Token", accessToken);
            headers.put("K-RealUser-IP", realUserIP);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("【快手】建组返回，accountId:{},---结果:{}", advertiserId, resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        Long unitId = dataJson.getLong("unit_id");
                        Thread.sleep(100);
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                getKuaiShouGroupService.getGroupByUnitId(accessToken, advertiserId, unitId);
                            }
                        };
                        thread.start();
                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                        returnMap.put("unitId", unitId);
                        returnMap.put("success", true);
                        //添加广告组和定向模板、人群包绑定关系
                  /*      Thread thread2 = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject request = new JSONObject();
                                    request.put("accountId", requestJson.getLong("advertiser_id"));
                                    request.put("unitId", unitId);
                                    JSONObject target = requestJson.getJSONObject("target");
                                    if (!Check.isNull(target)) {
                                        request.put("excludePopulation", target.getJSONArray("exclude_population"));
                                        request.put("population", target.getJSONArray("population"));
                                        request.put("paidAudience", target.getJSONArray("paid_audience"));
                                        populationGroupService.createPopulationAndGroupRel(request);
                                    }
                                    if (!Check.isNull(requestJson.getLong("template_id"))) {
                                        request.put("templateId", requestJson.getLong("template_id"));
                                        directionalPackageService.createUnitAndTemplate(request);
                                    }
                                    if (!Check.isNull(requestJson.getLong("app_id"))) {
                                        request.put("appId", requestJson.getLong("app_id"));
                                        appPackageService.createAppAndGroupRel(request);
                                    }
                                } catch (Exception e) {
                                    log.error("添加广告组和定向模板、人群包绑定关系异常，", e);
                                }
                            }
                        };
                        thread2.start();*/
                    }

                } else {
                    if (code == 400001 && resultJson.getString("message").equals("/rest/openapi/v2/ad_unit/create调用已超日限，次日可恢复调用")) {
                        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                        String key = advertiserId + "_" + nowDate + "unit_create_overrun";
                        redisUtil.set(key, 1, 60 * 60 * 24);
                    }
                    if (code == 500000 && count <= 4) {
                        adUnitCreate(accessToken, advertiserId, requestJson, count + 1);
                    }
                    log.error("创建[广告组]失败,账户ID:{},返回结果：{},------入参：{}", advertiserId, resultJson, requestJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创建广告组失败");
                    returnMap.put("success", false);
                }
            } else {
                if (count <= 4) {
                    log.info("创建组失败，重试，入参：{}", requestJson);
                    adUnitCreate(accessToken, advertiserId, requestJson, count + 1);
                }
                log.error("快手创建广告组回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                returnMap.put("code", -1);
                returnMap.put("message", "创建广告组异常");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建广告组失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "创建广告组错误");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @Override
    public void getCampaignList(CtopOauthToken token, Date startDate, Date endDate) {
        getCampaignListByPage(token.getAccessToken(), token.getAccountId(), startDate, endDate, 1);
    }

    private void getCampaignListByPage(String accessToken, Long accountId, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        param.put("page", page);
        param.put("page_size", 500);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        addCampaign(accountId, details);
        getCampaignListByPage(accessToken, accountId, startDate, endDate, page + 1);
    }


    @Override
    public JSONArray getCampaignList(CtopOauthToken token, Date startDate, Date endDate, int timeFilterType) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token.getAccessToken());
        headers.put("Content-Type", " application/json");
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        param.put("time_filter_type", timeFilterType);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{}", token.getAccountId());
            return null;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告计划信息返回结果异常,advertiserId:{},异常信息:{}", token.getAccountId(), resultJson);
            return null;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return null;
        }
        return details;
    }


    /**
     * 获取 单条 广告计划数据
     *
     * @param accessToken
     * @param advertiserId
     * @param campaignId
     */
    @Override
    public void getCampaign(String accessToken, Long advertiserId, Long campaignId) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        param.put("campaign_id", campaignId);
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_LIST;
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    JSONArray details = dataJson.getJSONArray("details");
                    if (!Check.isNull(details)) {
                        addCampaign(advertiserId, details);
                    }
                } else {
                    log.error("获取广告计划信息返回结果异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
                }
            } else {
                log.error("获取广告计划信息返回结果为空,advertiserId:{}", advertiserId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addCampaign(Long advertiserId, JSONArray details) {
        List<KuaiShouCampaign> campaigns = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detail = JSONObject.parseObject(details.get(i).toString());
            if (!Check.isNull(detail)) {
                KuaiShouCampaign campaign = new KuaiShouCampaign();
                campaign.setId("" + advertiserId + detail.getLong("campaign_id"));
                campaign.setAccountId(advertiserId);
                campaign.setCampaignId(detail.getLong("campaign_id"));
                campaign.setCampaignName(detail.getString("campaign_name"));
                campaign.setDayBudget(detail.getLong("day_budget"));
                if (!Check.isNull(detail.getJSONArray("day_budget_schedule"))) {
                    campaign.setDayBudgetSchedule(detail.getJSONArray("day_budget_schedule").toJSONString());
                }
                campaign.setStatus(detail.getInteger("status"));
                campaign.setPutStatus(detail.getInteger("put_status"));
                campaign.setCampaignType(detail.getInteger("campaign_type"));
                campaign.setCreateChannel(detail.getInteger("create_channel"));
                campaign.setPutCreateTime(detail.getString("create_time"));
                campaign.setPutUpdateTime(detail.getString("update_time"));
                campaign.setBidType(detail.getInteger("bid_type"));
                campaigns.add(campaign);
            }
        }
        kuaiShouCampaignService.replaceBatch(campaigns);
    }

    @Override
    public JSONArray getGroupList(CtopOauthToken token, Long campaignId, Date startDate,
                                  Date endDate, int time_filter_type) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GROUP_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }

        param.put("campaign_id", campaignId);

        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token.getAccessToken());
        headers.put("Content-Type", "application/json");

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告组接口异常,advertiserId:{}", token.getAccountId());
            return null;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告组返回结果异常,advertiserId:{},异常信息:{}", token.getAccountId(), resultJson);
            return null;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return null;
        }

        return details;
    }


    @Override
    public void getGroupList(CtopOauthToken token, Date startDate, Date endDate) {
        getGroupListByPage(token, startDate, endDate, 1);
    }


    @Autowired
    IRuleKuaiShouPlanService ruleKuaiShouPlanService;

    private void getGroupListByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GROUP_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", token.getAccountId());
        param.put("page_size", 500);
        param.put("page", page);
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", token.getAccessToken());
        headers.put("Content-Type", "application/json");

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告组接口异常,advertiserId:{}", token.getAccountId());
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告组返回结果异常,advertiserId:{},异常信息:{}", token.getAccountId(), resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        addGroup(token.getAccountId(), details);
        //   ruleKuaiShouPlanService.insertTarget(token.getAccountId(), details);
        getGroupListByPage(token, startDate, endDate, page + 1);
    }

    static ExecutorService executorBidTypeService = Executors.newFixedThreadPool(20);
    static ExecutorService executorMaxBidService = Executors.newFixedThreadPool(5);

    private void addGroup(Long accountId, JSONArray details) {
        JSONObject project = warningOperationService.getBidTypeAndMaxBid(accountId);
        if (Check.isNull(project) || Check.isNull(details)) {
            return;
        }

        // 最高出价
        Long maxBid = project.getLong("maxBid");

        //优化目标集
        List<Integer> bidList = null;
        String bidTypeStr = project.getString("bidType");
        if (!Check.isNull(bidTypeStr)) {
            bidList = JSONArray.parseArray(bidTypeStr, Integer.class);
        }

        //转化目标map
        Map<Integer, Long> ocpxMap = new HashMap<>();
        String ocpxTypeStr = project.getString("ocpxActionType");
        if (!Check.isNull(ocpxTypeStr)) {
            JSONArray ocpxArr = JSONArray.parseArray(ocpxTypeStr);
            for (int i = 0; i < ocpxArr.size(); i++) {
                JSONObject obj = ocpxArr.getJSONObject(i);
                ocpxMap.put(obj.getInteger("ocpxCode"), obj.getLong("maxValue"));
            }
        }

        //深度转化目标map
        Map<Integer, Long> deepMap = new HashMap<>();
        String deepTypeStr = project.getString("deepConversionType");
        if (!Check.isNull(deepTypeStr)) {
            JSONArray deepArr = JSONArray.parseArray(deepTypeStr);
            for (int i = 0; i < deepArr.size(); i++) {
                JSONObject obj = deepArr.getJSONObject(i);
                ocpxMap.put(obj.getInteger("deepCode"), obj.getLong("deepValue"));
            }
        }

        Map<Integer, String> textMap = new HashMap<>();
        List<JSONObject> lists = ocpxActionTypeConfigMapper.getKuaiShouOcpxTypeList();
        for (JSONObject da : lists) {
            textMap.put(da.getInteger("ocpxActionType"), da.getString("ocpxActionName"));
        }

        List<KuaiShouGroup> groups = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detail = JSONObject.parseObject(details.get(i).toString());
            if (!Check.isNull(detail)) {
                //优化目标
                Integer bidType = detail.getInteger("bid_type");
                //优化出价（只有单击时，才有值）
                Long bid = detail.getLong("bid");
                //转化目标
                Integer ocpxActionType = detail.getInteger("ocpx_action_type");
                //转化目标出价
                Long cpaBid = detail.getLong("cpa_bid");
                //深度转化目标
                Integer deepConversionType = detail.getInteger("deep_conversion_type");
                //深度转化目标出价
                Long deepConversionBid = detail.getLong("deep_conversion_bid");
                //单日预算
                Long dayBudget = detail.getLong("day_budget");
                //组ID
                Long unitId = detail.getLong("unit_id");
                //组名称
                String unitName = detail.getString("unit_name");
                //状态
                Integer status = detail.getInteger("status");
                //投放状态
                Integer putStatus = detail.getInteger("put_status");
                if (putStatus == 1 && status != 15) { // 组状态为 投放中的 and 广告组状态为非暂停
                    String msgType = "";
                    String msgBid = "";

                    Boolean typeFalg = true;
                    Boolean bidFalg = true;

                    //优化目标
                    if (!bidList.isEmpty()) {
                        if (!bidList.contains(bidType)) {
                            //项目不包含该优化目标，则关停
                            String msg = Check.isNull(textMap.get(bidType)) ? String.valueOf(bidType) : textMap.get(bidType);
                            msgType = "组优化目标：" + msg;
                            typeFalg = false;
                        } else if (bidType == 2 && bid > maxBid) {
                            //若优化目标为2点击数，并且广告组出价大于项目设置最大出价，则关停
                            bidFalg = false;
                            msgBid = "优化为点击且优化出价：" + bid + " > 项目最大出价：" + maxBid;
                        }
                    }
                    //转化目标
                    if (!Check.isNull(ocpxActionType) && ocpxActionType != 0) {
                        String msg = Check.isNull(textMap.get(ocpxActionType)) ? String.valueOf(ocpxActionType) : textMap.get(ocpxActionType);
                        //！=0是设置过转化目标
                        if (!Check.isNullMap(ocpxMap)) {
                            Long ocpxBid = ocpxMap.get(ocpxActionType);
                            if (Check.isNull(ocpxBid)) {
                                if (ocpxActionType == 2 && dayBudget != 0 && dayBudget <= 100 * 1000) {
                                    // 转化目标为2行为数，并且预算小于等于100且不是不限，则允许启动
                                    typeFalg = true;
                                } else {
                                    //通过key未获取值，说明不包含该目标，进行关停
                                    typeFalg = false;
                                    msgType = "组转化目标：" + msg + "，日预算为：" + dayBudget;
                                }
                            } else {
                                if (cpaBid > ocpxBid) {
                                    //组转化出价 大于 项目设置最大转化出价，则关停
                                    bidFalg = false;
                                    msgBid = "转化出价：" + cpaBid + " > 项目出价：" + ocpxBid;
                                }
                            }
                        } else if (ocpxActionType == 2 && (dayBudget == 0 || dayBudget > 100 * 1000)) {
                            // 转化目标为2行为数，并且预算大于100 或者不限，则关停
                            typeFalg = false;
                            msgType = "组转化目标：" + msg + "，日预算为：" + dayBudget;
                        }
                    }

                    //转化目标
                    if (!Check.isNull(deepConversionType) && deepConversionType != 0 && !deepMap.isEmpty()) {
                        String msg = Check.isNull(textMap.get(deepConversionType)) ? String.valueOf(deepConversionType) : textMap.get(deepConversionType);
                        Long deepBid = deepMap.get(deepConversionType);
                        if (Check.isNull(deepBid)) {
                            //通过key未获取值，说明不包含该目标，进行关停
                            typeFalg = false;
                            msgType = "组深度转化目标：" + msg;
                        } else {
                            if (deepConversionBid > deepBid) {
                                //组深度转化出价 大于 项目设置最大转化出价，则关停
                                bidFalg = false;
                                msgBid = "深度转化出价：" + deepConversionBid + " > 项目出价：" + deepBid;
                            }
                        }
                    }
                    String typeText = messageTemplate.getKuaiShouBidTypeMessage(project.getString("projectName"), accountId, unitId, unitName, msgType);
                    String bidText = messageTemplate.getKuaiShouBidMessage(project.getString("projectName"), accountId, unitId, unitName, msgBid);
                    if (!typeFalg) { // 出价方式设置非法
                        executorBidTypeService.submit(new Runnable() {
                            @Override
                            public void run() {
                                warningOperationService.kuaiShouWarningOperation(project.getLong("projectId"), typeText, accountId, unitId, unitName);
                            }
                        });
                    }
                    if (!bidFalg) {
                        executorMaxBidService.submit(new Runnable() {
                            @Override
                            public void run() {
                                warningOperationService.kuaiShouBidWarningOperation(project.getLong("projectId"), bidText, accountId, unitId, unitName);
                            }
                        });
                    }
                }

                KuaiShouGroup group = JSONObject.parseObject(detail.toJSONString(), KuaiShouGroup.class);
                group.setId("" + accountId + unitId);
                group.setAccountId(accountId);
                group.setGroupCreateTime(detail.getString("create_time"));
                group.setGroupUpdateTime(detail.getString("update_time"));
                group.setCreateTime(new Date());
                group.setUpdateTime(new Date());
                groups.add(group);
            }
        }
        if (!Check.isNull(groups)) {
            try {
                Thread.sleep(200L);
                groupMapper.replaceBatch(groups);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public JSONArray getCreativeList(CtopOauthToken token, Long unitId, Date startDate, Date endDate, int timeFilterType) {
        Long advertiserId = token.getAccountId();
        String accessToken = token.getAccessToken();

        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }

        param.put("unit_id", unitId);
        param.put("time_filter_type", timeFilterType);

        String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            log.error("获取广告创意返回结果为空,advertiserId:{}", advertiserId);
            return null;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", advertiserId, message);
            return null;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (null == details || details.size() <= 0) {
            return null;
        }
        return details;
    }


    @Override
    public void getCreativeList(CtopOauthToken token, Date startDate, Date endDate) {
        getCreativeListByPage(token.getAccessToken(), token.getAccountId(), startDate, endDate, 1);
    }


    public void getCreativeListByPage(String accessToken, Long advertiserId, Date startDate, Date endDate, Integer page) {
        try {


            Thread.sleep(1500);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", " application/json");
            headers.put("Access-Token", accessToken);
            JSONObject param = new JSONObject();
            param.put("advertiser_id", advertiserId);
            if (startDate != null && endDate != null) {
                param.put("start_date", DateUtils.formatDate(startDate));
                param.put("end_date", DateUtils.formatDate(endDate));
            }
            param.put("page_size", 500);
            param.put("page", page);

            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (Check.isNull(resultJson)) {
                log.error("获取广告创意返回结果为空,advertiserId:{}", advertiserId);
                return;
            }
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            if (null == code || code != 0) {
                log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", advertiserId, message);
                return;
            }
            JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
            if (null == details || details.size() <= 0) {
                return;
            }
            List<KuaiShouCreative> creatives = new ArrayList<>();
            for (int i = 0; i < details.size(); i++) {
                JSONObject detailJson = JSONObject.parseObject(details.get(i).toString());
                if (!Check.isNull(detailJson)) {
                    KuaiShouCreative creative = new KuaiShouCreative();
                    creative.setId("" + advertiserId + detailJson.getLong("creative_id"));
                    creative.setAccountId(advertiserId);
                    creative.setCampaignId(detailJson.getLong("campaign_id"));
                    creative.setUnitId(detailJson.getLong("unit_id"));
                    creative.setCreativeId(detailJson.getLong("creative_id"));
                    creative.setCreativeName(detailJson.getString("creative_name"));
                    creative.setCreativeMaterialType(detailJson.getInteger("creative_material_type"));
                    if (!Check.isNull(detailJson.getJSONArray("material_url"))) {
                        creative.setMaterialUrl(detailJson.getJSONArray("material_url").toJSONString());
                    }
                    if (!Check.isNull(detailJson.getJSONArray("image_tokens"))) {
                        creative.setImageTokens(detailJson.getJSONArray("image_tokens").toJSONString());
                    }
                    creative.setStatus(detailJson.getInteger("status"));
                    creative.setPutStatus(detailJson.getInteger("put_status"));
                    creative.setCreateChannel(detailJson.getInteger("create_channel"));
                    creative.setReviewDetail(detailJson.getString("review_detail"));
                    creative.setCoverUrl(detailJson.getString("cover_url"));
                    creative.setImageToken(detailJson.getString("image_token"));
                    creative.setCoverWidth(detailJson.getString("cover_width"));
                    creative.setCoverHeight(detailJson.getString("cover_height"));
                    creative.setOverlayBgUrl(detailJson.getString("overlay_bg_url"));
                    creative.setOverlayBgImageToken(detailJson.getString("overlay_bg_image_token"));
                    creative.setStickerTitle(detailJson.getString("sticker_title"));
                    creative.setOverlayType(detailJson.getString("overlay_type"));
                    creative.setClickTrackUrl(detailJson.getString("click_track_url"));
                    creative.setImpressionUrl(detailJson.getString("impression_url"));
                    creative.setAdPhotoPlayedT3sUrl(detailJson.getString("ad_photo_played_t3s_url"));
                    creative.setCreativeCreateTime(detailJson.getDate("create_time"));
                    creative.setCreativeUpdateTime(detailJson.getDate("update_time"));
                    creative.setFirstFrameType(detailJson.getInteger("first_frame_type"));
                    creative.setShortSlogan(detailJson.getString("short_slogan"));
                    creative.setCreativeCategory(detailJson.getInteger("creative_category"));
                    if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                        creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                    }
                    creative.setActionbarClickUrl(detailJson.getString("actionbar_click_url"));
                    JSONObject displayInfoJson = detailJson.getJSONObject("display_info");
                    if (!Check.isNull(displayInfoJson)) {
                        creative.setDescription(displayInfoJson.getString("description"));
                        creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                    }
                    creative.setCreateTime(new Date());
                    creative.setUpdateTime(new Date());
                    creative.setSiteId(detailJson.getLong("site_id"));
                    creative.setPhotoId(detailJson.getString("photo_id"));
                    if (detailJson.getLong("photo_id") == 0) {
                        JSONArray photoIds = new JSONArray();
                        JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                        if (!Check.isNull(programmed_creative_material)) {
                            creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                            JSONArray materials = programmed_creative_material.getJSONArray("materials");
                            if (!Check.isNull(materials)) {
                                for (int j = 0; j < materials.size(); j++) {
                                    JSONObject materialJson = materials.getJSONObject(j);
                                    if (!Check.isNull(materialJson)) {
                                        Long photo_id = materialJson.getLong("photo_id");
                                        photoIds.add(String.valueOf(photo_id));
                                    }
                                }
                                creative.setPhotoIds(photoIds.toJSONString());
                            }
                        }
                    }
                    creatives.add(creative);
                }

            }
            creativeService.replaceBatch(creatives);
            getCreativeListByPage(accessToken, advertiserId, startDate, endDate, page + 1);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    /**
     * 获取视频信息数据
     *
     * @param accessToken
     * @param accountId
     * @param photoId
     */
    @Override
    public void getVideoInfo(String accessToken, Long accountId, String photoId) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_GET;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        JSONArray photosArray = new JSONArray();
        photosArray.add(photoId);
        param.put("photo_ids", photosArray);
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONArray details = resultJson.getJSONArray("data");
                    if (Check.isNull(details)) {
                        return;
                    }
                    List<KuaiShouVideoGet> videoGetList = new ArrayList<>();
                    for (int i = 0; i < details.size(); i++) {
                        JSONObject detailJson = details.getJSONObject(i);
                        if (Check.isNull(detailJson)) {
                            continue;
                        }
                        KuaiShouVideoGet videoGet = new KuaiShouVideoGet();
                        String photo_id = detailJson.getString("photo_id");
                        videoGet.setId(accountId + photo_id);
                        videoGet.setAccountId(accountId);
                        videoGet.setCoverUrl(detailJson.getString("cover_url"));

                        videoGet.setPhotoId(photo_id);
                        videoGet.setPhotoName(detailJson.getString("photo_name"));
                        videoGet.setStatDate(detailJson.getDate("upload_time"));
                        String signature = detailJson.getString("signature");
                        videoGet.setSignature(signature);
                        Integer source = detailJson.getInteger("source");
                        if (source == 2) {
                            videoGet.setChannelType(1);
                        } else {
                            videoGet.setChannelType(0);
                        }
                        Integer new_status = detailJson.getInteger("new_status");
                        if (new_status == 1) {
                            videoGet.setStatus(0);
                        } else {
                            videoGet.setStatus(1);
                        }
                        videoGet.setUrl(detailJson.getString("url"));
                        Integer width = detailJson.getInteger("width");
                        videoGet.setWidth(width);
                        Integer height = detailJson.getInteger("height");
                        videoGet.setHeight(height);
                        Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(width, height);
                        if (!Check.isNullMap(typeBySize)) {
                            videoGet.setMaterialType(typeBySize.get("type"));
                            videoGet.setIsKaiPing(typeBySize.get("isKaiPing"));
                        }
                        videoGetList.add(videoGet);
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                videoGetService.getKeyFrame(accessToken, accountId, signature, photo_id);
                            }
                        };
                        thread.start();
                    }
                    if (!Check.isNull(videoGetList)) {
                        videoGetService.replaceBatch(videoGetList);
                    }

                } else {
                    log.error("获取广告视频信息返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
                }

            } else {
                log.error("获取广告视频信息返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            }
        } catch (
                Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 获取 创意信息
     *
     * @param accessToken
     * @param advertiserId
     */
    @Override
    public void getCreativeByCreativeId(String accessToken, Long advertiserId, Long creativeId) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        param.put("creative_id", creativeId);
        param.put("page_size", 200);
        param.put("page", 1);
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray details = dataJson.getJSONArray("details");
                        if (!Check.isNull(details)) {
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject detailJson = JSONObject.parseObject(details.get(i).toString());
                                if (!Check.isNull(detailJson)) {
                                    KuaiShouCreative creative = new KuaiShouCreative();
                                    creative.setId("" + advertiserId + detailJson.getLong("creative_id"));
                                    creative.setAccountId(advertiserId);
                                    creative.setCampaignId(detailJson.getLong("campaign_id"));
                                    creative.setUnitId(detailJson.getLong("unit_id"));
                                    creative.setCreativeId(detailJson.getLong("creative_id"));
                                    creative.setCreativeName(detailJson.getString("creative_name"));
                                    creative.setCreativeMaterialType(detailJson.getInteger("creative_material_type"));
                                    if (!Check.isNull(detailJson.getJSONArray("material_url"))) {
                                        creative.setMaterialUrl(detailJson.getJSONArray("material_url").toJSONString());
                                    }

                                    if (!Check.isNull(detailJson.getJSONArray("image_tokens"))) {
                                        creative.setImageTokens(detailJson.getJSONArray("image_tokens").toJSONString());
                                    }
                                    creative.setStatus(detailJson.getInteger("status"));
                                    creative.setPutStatus(detailJson.getInteger("put_status"));
                                    creative.setCreateChannel(detailJson.getInteger("create_channel"));
                                    creative.setReviewDetail(detailJson.getString("review_detail"));
                                    creative.setCoverUrl(detailJson.getString("cover_url"));
                                    creative.setImageToken(detailJson.getString("image_token"));
                                    creative.setCoverWidth(detailJson.getString("cover_width"));
                                    creative.setCoverHeight(detailJson.getString("cover_height"));
                                    creative.setOverlayBgUrl(detailJson.getString("overlay_bg_url"));
                                    creative.setOverlayBgImageToken(detailJson.getString("overlay_bg_image_token"));
                                    creative.setStickerTitle(detailJson.getString("sticker_title"));
                                    creative.setOverlayType(detailJson.getString("overlay_type"));
                                    creative.setClickTrackUrl(detailJson.getString("click_track_url"));
                                    creative.setImpressionUrl(detailJson.getString("impression_url"));
                                    creative.setAdPhotoPlayedT3sUrl(detailJson.getString("ad_photo_played_t3s_url"));
                                    creative.setCreativeCreateTime(detailJson.getDate("create_time"));
                                    creative.setCreativeUpdateTime(detailJson.getDate("update_time"));
                                    creative.setFirstFrameType(detailJson.getInteger("first_frame_type"));
                                    creative.setShortSlogan(detailJson.getString("short_slogan"));
                                    creative.setActionbarClickUrl(detailJson.getString("actionbar_click_url"));
                                    JSONObject displayInfoJson = detailJson.getJSONObject("display_info");

                                    creative.setCreativeCategory(detailJson.getInteger("creative_category"));
                                    if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                                        creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                                    }

                                    if (!Check.isNull(displayInfoJson)) {
                                        creative.setDescription(displayInfoJson.getString("description"));
                                        creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                                    }
                                    creative.setCreateTime(new Date());
                                    creative.setUpdateTime(new Date());
                                    creative.setSiteId(detailJson.getLong("site_id"));
                                    creative.setPhotoId(detailJson.getString("photo_id"));
                                    if (detailJson.getLong("photo_id") == 0) {
                                        JSONArray photoIds = new JSONArray();
                                        JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                                        if (!Check.isNull(programmed_creative_material)) {
                                            creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                                            JSONArray materials = programmed_creative_material.getJSONArray("materials");
                                            if (!Check.isNull(materials)) {
                                                for (int j = 0; j < materials.size(); j++) {
                                                    JSONObject materialJson = materials.getJSONObject(j);
                                                    if (!Check.isNull(materialJson)) {
                                                        Long photo_id = materialJson.getLong("photo_id");
                                                        photoIds.add(String.valueOf(photo_id));
                                                    }
                                                }
                                                creative.setPhotoIds(photoIds.toJSONString());
                                            }
                                        }
                                    }
                                    creativeService.saveOrUpdate(creative);
                                }

                            }

                        }
                    }
                } else {
                    log.error("获取广告创意组返回结果异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
                }

            } else {
                log.error("获取广告创意返回结果异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void getCreativeByCreativeIds(String accessToken, Long advertiserId, JSONArray creativeIds) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", " application/json");
        headers.put("Access-Token", accessToken);
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        //  param.put("creative_id", creativeId);
        if (!Check.isNull(creativeIds)) {
            param.put("creative_ids", creativeIds);
        }
        param.put("page_size", 200);
        param.put("page", 1);
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray details = dataJson.getJSONArray("details");
                        if (!Check.isNull(details)) {
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject detailJson = JSONObject.parseObject(details.get(i).toString());
                                if (!Check.isNull(detailJson)) {
                                    KuaiShouCreative creative = new KuaiShouCreative();
                                    creative.setId("" + advertiserId + detailJson.getLong("creative_id"));
                                    creative.setAccountId(advertiserId);
                                    creative.setCampaignId(detailJson.getLong("campaign_id"));
                                    creative.setUnitId(detailJson.getLong("unit_id"));
                                    creative.setCreativeId(detailJson.getLong("creative_id"));
                                    creative.setCreativeName(detailJson.getString("creative_name"));
                                    creative.setCreativeMaterialType(detailJson.getInteger("creative_material_type"));
                                    if (!Check.isNull(detailJson.getJSONArray("material_url"))) {
                                        creative.setMaterialUrl(detailJson.getJSONArray("material_url").toJSONString());
                                    }

                                    if (!Check.isNull(detailJson.getJSONArray("image_tokens"))) {
                                        creative.setImageTokens(detailJson.getJSONArray("image_tokens").toJSONString());
                                    }
                                    creative.setStatus(detailJson.getInteger("status"));
                                    creative.setPutStatus(detailJson.getInteger("put_status"));
                                    creative.setCreateChannel(detailJson.getInteger("create_channel"));
                                    creative.setReviewDetail(detailJson.getString("review_detail"));
                                    creative.setCoverUrl(detailJson.getString("cover_url"));
                                    creative.setImageToken(detailJson.getString("image_token"));
                                    creative.setCoverWidth(detailJson.getString("cover_width"));
                                    creative.setCoverHeight(detailJson.getString("cover_height"));
                                    creative.setOverlayBgUrl(detailJson.getString("overlay_bg_url"));
                                    creative.setOverlayBgImageToken(detailJson.getString("overlay_bg_image_token"));
                                    creative.setStickerTitle(detailJson.getString("sticker_title"));
                                    creative.setOverlayType(detailJson.getString("overlay_type"));
                                    creative.setClickTrackUrl(detailJson.getString("click_track_url"));
                                    creative.setImpressionUrl(detailJson.getString("impression_url"));
                                    creative.setAdPhotoPlayedT3sUrl(detailJson.getString("ad_photo_played_t3s_url"));
                                    creative.setCreativeCreateTime(detailJson.getDate("create_time"));
                                    creative.setCreativeUpdateTime(detailJson.getDate("update_time"));
                                    creative.setFirstFrameType(detailJson.getInteger("first_frame_type"));
                                    creative.setShortSlogan(detailJson.getString("short_slogan"));
                                    creative.setActionbarClickUrl(detailJson.getString("actionbar_click_url"));
                                    JSONObject displayInfoJson = detailJson.getJSONObject("display_info");

                                    creative.setCreativeCategory(detailJson.getInteger("creative_category"));
                                    if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                                        creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                                    }

                                    if (!Check.isNull(displayInfoJson)) {
                                        creative.setDescription(displayInfoJson.getString("description"));
                                        creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                                    }
                                    creative.setCreateTime(new Date());
                                    creative.setUpdateTime(new Date());
                                    creative.setSiteId(detailJson.getLong("site_id"));
                                    creative.setPhotoId(detailJson.getString("photo_id"));
                                    if (detailJson.getLong("photo_id") == 0) {
                                        JSONArray photoIds = new JSONArray();
                                        JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                                        if (!Check.isNull(programmed_creative_material)) {
                                            creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                                            JSONArray materials = programmed_creative_material.getJSONArray("materials");
                                            if (!Check.isNull(materials)) {
                                                for (int j = 0; j < materials.size(); j++) {
                                                    JSONObject materialJson = materials.getJSONObject(j);
                                                    if (!Check.isNull(materialJson)) {
                                                        Long photo_id = materialJson.getLong("photo_id");
                                                        photoIds.add(String.valueOf(photo_id));
                                                    }
                                                }
                                                creative.setPhotoIds(photoIds.toJSONString());
                                            }
                                        }
                                    }
                                    creativeService.saveOrUpdate(creative);
                                }

                            }

                        }
                    }
                } else {
                    log.error("获取广告创意组返回结果异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
                }

            } else {
                log.error("获取广告创意返回结果异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取token
     *
     * @param authCode
     * @return
     */
    @Autowired
    private IOauthConfigService configService;

    @Override
    public KuaishouResultToken getAccessToken(String authCode, Long appId) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AUTH_TOKEN;
        JSONObject requestJson = new JSONObject();
        requestJson.put("auth_code", authCode);

        OauthConfig config = configService.getConfigByAppId(appId);
        requestJson.put("app_id", config.getAppId());
        requestJson.put("secret", config.getSecret());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        KuaishouResultToken kuaiShouResult = null;
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            log.info("返回token信息：{}", JSONObject.parseObject(result));
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            kuaiShouResult = mapper.readValue(result, new TypeReference<KuaishouResultToken>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaiShouResult;
    }


    @Override
    public JSONObject getDeepConversionInfosV2(Long advertiserId, String accessToken, Integer campaignType, Long appId) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.DEEP_CONVERSION_INFOS;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        if (!Check.isNull(campaignType)) {
            param.put("campaign_type", campaignType);
        }
        if (!Check.isNull(appId)) {
            param.put("app_id", appId);
        }
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info(resultJson.toJSONString());
            if (!Check.isNullMap(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNullMap(dataJson)) {
                        JSONObject returnJson = new JSONObject();
                        returnJson.put("isActivate", dataJson.getInteger("is_activate"));
                        returnJson.put("isFormSubmit", dataJson.getInteger("is_form_submit"));
                        returnJson.put("isCreditGrant", dataJson.getInteger("is_credit_grant"));
                        returnJson.put("isWanJian", dataJson.getInteger("is_wan_jian"));
                        returnJson.put("isValidClue", dataJson.getInteger("is_valid_clue"));
                        returnJson.put("isPurchase", dataJson.getInteger("is_purchase"));
                        returnJson.put("isFirstdayRoi", dataJson.getInteger("is_firstday_roi"));
                        returnJson.put("isRegister", dataJson.getInteger("is_register"));
                        returnJson.put("isOrderSubmit", dataJson.getInteger("is_order_submit"));
                        returnJson.put("isAddWechat", dataJson.getInteger("is_add_wechat"));
                        returnJson.put("isAppInvoked", dataJson.getInteger("is_app_invoked"));
                        returnJson.put("isAdWatchTimes", dataJson.getInteger("is_ad_watch_times"));
                        returnJson.put("isMultiConversion", dataJson.getInteger("is_multi_conversion"));
                        returnJson.put("isOrderPaied", dataJson.getInteger("is_order_paied"));
                        returnJson.put("isEventWeekPayTimes", dataJson.getInteger("is_event_week_pay_times"));
                        returnJson.put("isKeyAction", dataJson.getInteger("is_key_action"));
                        returnJson.put("isAppointForm", dataJson.getInteger("is_appoint_form"));
                        returnJson.put("isSevenDayRoi", dataJson.getInteger("is_seven_day_roi"));
                        returnJson.put("isAdWatch10Times", dataJson.getInteger("is_ad_watch_10_times"));
                        returnJson.put("isAdWatch20Times", dataJson.getInteger("is_ad_watch_20_times"));
                        returnJson.put("isAdWatch5Times", dataJson.getInteger("is_ad_watch_5_times"));

                        JSONArray deep_conversion_types = dataJson.getJSONArray("deep_conversion_types");
                        JSONArray deepConversionTypes = new JSONArray();
                        if (!Check.isNull(deep_conversion_types)) {
                            for (int i = 0; i < deep_conversion_types.size(); i++) {
                                JSONObject json = new JSONObject();
                                JSONObject deepConversion = deep_conversion_types.getJSONObject(i);
                                json.put("desc", deepConversion.getString("desc"));
                                json.put("deepConversionType", deepConversion.getInteger("deep_conversion_type"));
                                deepConversionTypes.add(json);
                            }
                        }
                        returnJson.put("deepConversionTypes", deepConversionTypes);
                        return returnJson;
                    }
                } else {
                    log.error("获取可选的深度转化类型返回异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);

                }
            } else {
                log.error("快手，获取可选的深度转化类型返回为空，advertiserId：{}", advertiserId);

            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;

    }

    @Override
    public JSONObject conversionInfos(Long advertiserId, String accessToken, Integer sceneCategory, Integer campaignType, JSONArray sceneIds, Long appId) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/v1/ocpx/ocpxTypes";
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        if (!Check.isNull(campaignType)) {
            param.put("campaign_type", campaignType);
        }
        if (!Check.isNull(appId)) {
            param.put("app_id", appId);
        }
        if (!Check.isNull(sceneCategory)) {
            param.put("scene_category", sceneCategory);
        }

        if (!Check.isNull(sceneIds)) {
            param.put("scene_ids", sceneIds);
        }
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject returnJson = new JSONObject();
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            returnJson = JSONObject.parseObject(result);
            if (Check.isNull(returnJson)) {
                returnJson.put("code", -1);
                returnJson.put("message", "返回信息为空");
            }

        } catch (Exception e) {
            returnJson.put("code", -1);
            returnJson.put("message", "系统错误");

        }
        return returnJson;

    }

    @Override
    public JSONObject deepTypes(Long accountId, String accessToken, Integer sceneCategory, Integer campaignType, JSONArray sceneIds, Long appId, Integer ocpxActionType) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/v1/ocpx/deepTypes";
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (!Check.isNull(campaignType)) {
            param.put("campaign_type", campaignType);
        }
        if (!Check.isNull(appId)) {
            param.put("app_id", appId);
        }
        if (!Check.isNull(sceneCategory)) {
            param.put("scene_category", sceneCategory);
        }
        if (!Check.isNull(sceneIds)) {
            param.put("scene_ids", sceneIds);
        }
        if (!Check.isNull(ocpxActionType)) {
            param.put("ocpx_action_type", ocpxActionType);
        }
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject returnJson = new JSONObject();
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            returnJson = JSONObject.parseObject(result);
            if (Check.isNull(returnJson)) {
                returnJson.put("code", -1);
                returnJson.put("message", "返回信息为空");
            }

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

        }
        return returnJson;
    }


    /**
     * 创建广告创意
     *
     * @param accessToken
     * @param advertiserId
     * @param requestJson
     */

    @Autowired
    private IKuaiShouOverRunSendMessageService overRunSendMessageService;
    @Autowired
    private IAiCreativeLimitService creativeLimitService;

    @Override
    public Map<String, Object> creativeCreate(String accessToken, Long advertiserId, JSONObject requestJson, Integer count) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_CREATIVE_CREATE;
            requestJson.put("advertiser_id", advertiserId);
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", " application/json");
            header.put("K-RealUser-IP", realUserIP);
            header.put("Access-Token", accessToken);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), header);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("【快手】建创意返回，accountId:{},---结果:{}", advertiserId, resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        Long creativeId = dataJson.getLong("creative_id");
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(100);
                                    getCreativeByCreativeId(accessToken, advertiserId, creativeId);
//                                    //绑定落地页与广告组、创意的关系
//                                    if (!Check.isNull(requestJson.getLong("site_id"))) {
//                                        landpagePackageService.createLandPageAndUnit(requestJson.getLong("site_id"), creativeId, requestJson.getLong("unit_id"), advertiserId);
//                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }

                        };
                        thread.start();
                        returnMap.put("code", 0);
                        returnMap.put("creativeId", creativeId);
                        returnMap.put("message", "success");
                        returnMap.put("success", true);
                    }
                } else {
                    if (code == 500000 && count <= 4) {
                        creativeCreate(accessToken, advertiserId, requestJson, count + 1);
                    }
                    if (code == 400001 && "/rest/openapi/v2/creative/create调用已超日限，次日可恢复调用".equals(resultJson.getString("message"))) {
                        creativeOverrunInfoService.updateOverrunInfo(advertiserId);
                        overRunSendMessageService.creativeOverRunSendMessage(advertiserId, null);
                        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
                        String key = advertiserId + "_" + nowDate + "creative_create_overrun";
                        redisUtil.set(key, 1, 60 * 60 * 24);
                    }
                    if (code == 401000 && resultJson.getString("message").contains("超过可关联的有效创意的上限")) {
                        creativeLimitService.replaceSava(advertiserId, requestJson.getLong("photo_id"));
                    }
                    if (code == 401000 && resultJson.getString("message").contains("视频不存在")) {
                        creativeLimitService.replaceSava(advertiserId, requestJson.getLong("photo_id"));
                    }
                    log.error("创建[广告创意]失败,账户ID:{},返回结果：{},------入参：{}", advertiserId, resultJson, requestJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创意创建失败");
                    returnMap.put("success", false);
                }
            } else {
                if (count <= 4) {
                    creativeCreate(accessToken, advertiserId, requestJson, count + 1);
                }
                log.error("快手创建广告创意返回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                returnMap.put("code", -1);
                returnMap.put("message", "result is null");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建广告创意失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "error");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;

    }

    @Autowired
    private IKuaishouAccountCreativeOverrunInfoService creativeOverrunInfoService;

    @Override
    public Map<String, Object> batchCreativeCreate(String accessToken, Long advertiserId, JSONObject requestJson, Integer count, String userId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = "https://ad.e.kuaishou.com/rest/openapi/v2/creative/batch/update";
            requestJson.put("advertiser_id", advertiserId);
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", " application/json");
            header.put("Access-Token", accessToken);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), header);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("快手创建创意返回：accountId:{}，返回结果{}", advertiserId, resultJson);
            if (!Check.isNull(resultJson)) {
                String message = resultJson.getString("message");
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray add_creative_ids = dataJson.getJSONArray("add_creative_ids");
                        if (!Check.isNull(add_creative_ids)) {
                            Thread thread = new Thread() {
                                @Override
                                public void run() {
                                    try {
                                        Thread.sleep(100);
                                        getCreativeByCreativeIds(accessToken, advertiserId, add_creative_ids);
//                                        createLandPageAndUnit(requestJson, add_creative_ids);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }

                                }

                            };
                            thread.start();
                        }

                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                        returnMap.put("success", true);
                        returnMap.put("count", add_creative_ids.size());
                        returnMap.put("ids", add_creative_ids);
                    }
                } else {
                    if (code == 500000 && count <= 4) {
                        batchCreativeCreate(accessToken, advertiserId, requestJson, count + 1, userId);
                    } else if (code == 400001 && message.contains("已超日限")) {
                        overRunSendMessageService.creativeOverRunSendMessage(advertiserId, userId);
                    }else if (message.contains("过于频繁")&& count <= 4) {
                        batchCreativeCreate(accessToken, advertiserId, requestJson, count + 1, userId);
                    }
                    log.error("创建广告创意失败,advertiser_id:{},返回信息：{}，入参：{}", advertiserId, resultJson, requestJson, count + 1);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创意创建失败");
                    returnMap.put("success", false);
                }
            } else {
                if (count <= 4) {
                    batchCreativeCreate(accessToken, advertiserId, requestJson, count + 1, userId);
                }

                log.error("快手创建广告创意返回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                returnMap.put("code", -1);
                returnMap.put("message", "系统异常");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }

        } catch (Exception e) {
            log.error("创建广告创意失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "error");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;

    }

    //绑定落地页与广告组、创意的关系
    private void createLandPageAndUnit(JSONObject programJson, JSONArray add_creative_ids) {
        JSONArray creatives = programJson.getJSONArray("creatives");
        if (creatives != null && !creatives.isEmpty()) {
            JSONObject jsonObject = creatives.getJSONObject(0);
            Long siteId = jsonObject.getLong("site_id");
            if (!Check.isNull(siteId)) {
                if (!Check.isNull(jsonObject)) {
                    for (Object creativeId : add_creative_ids) {
                        landpagePackageService.createLandPageAndUnit(siteId, Long.valueOf(String.valueOf(creativeId)), programJson.getLong("unit_id"), programJson.getLong("advertiser_id"));
                    }
                }
            }
        }
    }

    /**
     * 获取视频信息
     *
     * @param advertiserId
     * @param accessToken
     */
    @Override
    public void videoGet(Long advertiserId, String accessToken, String photoId, String signature) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_GET;
            JSONObject param = new JSONObject();
            param.put("advertiser_id", advertiserId);
            ArrayList<String> strArray = new ArrayList<String>();
            strArray.add(photoId);
            param.put("photo_ids", strArray);
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONArray dataArr = resultJson.getJSONArray("data");
                    if (!Check.isNull(dataArr)) {
                        for (int i = 0; i < dataArr.size(); i++) {
                            JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                            if (!Check.isNull(dataJson)) {
                                KuaiShouVideoGet videoGet = new KuaiShouVideoGet();
                                videoGet.setAccountId(advertiserId);
                                videoGet.setId(advertiserId + signature);
                                videoGet.setWidth(dataJson.getInteger("width"));
                                videoGet.setHeight(dataJson.getInteger("height"));
                                videoGet.setUrl(dataJson.getString("url"));
                                videoGet.setPhotoId(dataJson.getString("photo_id"));
                                videoGet.setCoverUrl(dataJson.getString("cover_url"));
                                videoGet.setStatus(dataJson.getInteger("new_status"));
                                Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                                if (!Check.isNullMap(typeBySize)) {
                                    videoGet.setMaterialType(typeBySize.get("type"));
                                    videoGet.setIsKaiPing(typeBySize.get("isKaiPing"));
                                }
                                videoGet.setSignature(signature);
                                kuaiShouVideoGetService.saveOrUpdate(videoGet);

                            }
                        }
                    }
                    log.info("获取视频信息完成,advertiserId:{},返回信息：{}", advertiserId, resultJson);
                } else {
                    log.error("获取广告视频失败,advertiser_id:{},返回信息：{}", advertiserId, resultJson);
                }
            } else {
                log.error("获取视频信息返回结果为空，advertiserId：{}", advertiserId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取图片信息
     *
     * @param advertiserId
     * @param accessToken
     * @param imageToken
     */


    @Override
    public void imageGet(Long advertiserId, String accessToken, String imageToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_GET;
            JSONObject param = new JSONObject();
            param.put("advertiser_id", advertiserId);
            param.put("image_token", imageToken);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    log.info("获取完成，返回数据：{}", dataJson);
                    if (!Check.isNull(dataJson)) {
                        String signature = dataJson.getString("signature");
                        KuaiShouImageGet imageGet = new KuaiShouImageGet();
                        imageGet.setId(advertiserId + signature);
                        imageGet.setAccountId(advertiserId);
                        imageGet.setUrl(dataJson.getString("url"));
                        imageGet.setWidth(dataJson.getInteger("width"));
                        imageGet.setHeight(dataJson.getInteger("height"));
                        imageGet.setSize(dataJson.getInteger("size"));
                        imageGet.setFormat(dataJson.getString("format"));
                        Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                        if (!Check.isNullMap(typeBySize)) {
                            imageGet.setMaterialType(typeBySize.get("type"));
                        }
                        imageGet.setSignature(signature);
                        imageGet.setImageToken(dataJson.getString("image_token"));
                        iKuaiShouImageGetService.saveOrUpdate(imageGet);
                    }
                } else {
                    log.error("获取广告图片失败,advertiser_id:{},返回信息：{}", advertiserId, resultJson);
                }
            } else {
                log.error("获取图片信息返回结果为空，advertiserId：{}", advertiserId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 地域列表
     *
     * @param accessToken
     */
    @Override
    public void areaList(String accessToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.REGION_LIST;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.httpGet(url, null, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    regionListParentMapper.deleteAll();
                    regionListChildrenMapper.deleteAll();
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
                            String key = entry.getKey();
                            JSONObject keyJson = dataJson.getJSONObject(key);
                            if (!Check.isNull(keyJson)) {
                                KuaiShouRegionListParent regionListParent = new KuaiShouRegionListParent();
                                Long id = keyJson.getLong("id");
                                regionListParent.setRegionId(id);
                                regionListParent.setLevel(keyJson.getInteger("level"));
                                regionListParent.setName(keyJson.getString("name"));
                                regionListParent.setParent(keyJson.getLong("parent"));
                                regionListParentMapper.insert(regionListParent);
                                JSONArray childrenArr = keyJson.getJSONArray("children");
                                if (!Check.isNull(childrenArr)) {
                                    for (int i = 0; i < childrenArr.size(); i++) {
                                        KuaiShouRegionListChildren regionListChildren = new KuaiShouRegionListChildren();
                                        regionListChildren.setParentId(id);
                                        regionListChildren.setRegionId(childrenArr.getLong(i));
                                        regionListChildrenMapper.insert(regionListChildren);

                                    }
                                }
                            }
                        }
                    }
                } else {
                    log.error("获取地域列表失败");
                }
            } else {
                log.error("获取地域列表返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取快手广告租信息
     *
     * @param accountId
     * @param accessToken
     * @return
     */
    @Override
    public Map<String, Object> advertiserInfo(Long accountId, String accessToken) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("account_id", accountId);
            advertiserBaseInfoMapper.deleteByMap(deleteMap);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.ADVERTISER_INFO;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getInteger("code") == 0) {
                JSONObject dataJson = resultJson.getJSONObject("data");
                if (!Check.isNull(dataJson)) {
                    KuaiShouAdvertiserBaseInfo advertiserBaseInfo = new KuaiShouAdvertiserBaseInfo();
                    advertiserBaseInfo.setAccountId(accountId);
                    advertiserBaseInfo.setUserId(dataJson.getString("user_id"));
                    String corporationName = dataJson.getString("corporation_name");
                    advertiserBaseInfo.setCorporationName(corporationName);
                    String userName = dataJson.getString("user_name");
                    advertiserBaseInfo.setUserName(userName);
                    returnMap.put("code", 0);
                    returnMap.put("message", "success");
                    returnMap.put("userName", userName);
                    returnMap.put("corporationName", corporationName);
                    int i = advertiserBaseInfoMapper.insert(advertiserBaseInfo);
                    if (i > 0) {
                        log.info("快手获取广告主基本信息入库完成，accountId:{}", accountId);
                    }
                } else {
                    log.error("快手获取广告主基本信息返回为空,accountId:{}", accountId);
                    returnMap.put("code", -1);
                    returnMap.put("message", "返回信息为空");
                }

            } else {
                log.error("快手获取广告主基本信息返回错误,accountId:{},错误信息:{}", accountId, resultJson);
                returnMap.put("code", -1);
                returnMap.put("message", resultJson.getString("message"));
            }

        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("message", "接口执行失败");
        }
        return returnMap;
    }


    /*@Override
    public void getAppList(Long advertiserId, String accessToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            JSONObject json = new JSONObject();
            json.put("advertiser_id", advertiserId);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    Map<String, Object> deleteMap = new HashMap<>();
                    deleteMap.put("account_id", advertiserId);
                    appListMapper.deleteByMap(deleteMap);
                    JSONArray dataArr = resultJson.getJSONArray("data");
                    if (!Check.isNull(dataArr)) {
                        for (int i = 0; i < dataArr.size(); i++) {
                            JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                            if (!Check.isNull(dataJson)) {
                                KuaiShouAppList appList = new KuaiShouAppList();
                                appList.setAccountId(advertiserId);
                                appList.setPlatform(dataJson.getInteger("platform"));
                                appList.setUrl(dataJson.getString("url"));
                                appList.setAppId(dataJson.getLong("app_id"));
                                appList.setAppVersion(dataJson.getString("app_version"));
                                appList.setAppName(dataJson.getString("app_name"));
                                appList.setAppIconUrl(dataJson.getString("app_icon_url"));
                                appList.setImageToken(dataJson.getString("image_token"));
                                appList.setPackageName(dataJson.getString("package_name"));
                                appList.setReturnTime(DateUtils.timeStamp2Date(dataJson.getTimestamp("update_time")));
                                appListMapper.insert(appList);
                            }
                        }
                    }
                } else {
                    log.error("获取应用列表失败，返回信息：{}", resultJson);
                }
            } else {
                log.error("获取地域列表返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/


    public Object jsonToObj(Object t, String jsonStr) throws
            JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();

        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(jsonStr, new TypeReference<Object>() {
        });
    }

    public JavaType getJavaType(Type type) {
        //判断是否带有泛型
        if (type instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
            //获取泛型类型
            Class rowClass = (Class) ((ParameterizedType) type).getRawType();
            JavaType[] javaTypes = new JavaType[actualTypeArguments.length];
            for (int i = 0; i < actualTypeArguments.length; i++) {
                //泛型也可能带有泛型，递归获取
                javaTypes[i] = getJavaType(actualTypeArguments[i]);
            }
            return TypeFactory.defaultInstance().constructParametricType(rowClass, javaTypes);
        } else {
            //简单类型直接用该类构建
            Class cla = (Class) type;
            return TypeFactory.defaultInstance().constructParametricType(cla, new JavaType[0]);
        }
    }

    @Override
    public String exceptInfoForRestTemplate(String url, Map<String, Object> paramMap, Map<String, String> headerMap, String filePath) throws ParseException {
        try {
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            if (!Check.isNull(filePath)) {
                FileSystemResource resource = new FileSystemResource(new File(filePath));
                param.add("file", resource);
            }
            if (!Check.isNullMap(paramMap)) {
                for (String key : paramMap.keySet()) {
                    param.add(key, paramMap.get(key));
                }
                HttpHeaders headers = new HttpHeaders();
                if (!Check.isNullMap(headerMap)) {
                    for (String key : headerMap.keySet()) {
                        headers.add(key, headerMap.get(key));
                    }
                }
                SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
                requestFactory.setConnectTimeout(1000 * 500);// 设置超时
                requestFactory.setReadTimeout(1000 * 500);
                RestTemplate rest = new RestTemplate(requestFactory);
                HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param, headers);
                ResponseEntity<String> responseEntity = rest.exchange(url, HttpMethod.POST, httpEntity, String.class);
                return responseEntity.getBody();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 查询图片列表
     */
    @Override
    public void getImageList(CtopOauthToken token, String statDate) {
        getImageList(token, statDate, 1);
    }


    /**
     * 查询图片列表
     */
    private void getImageList(CtopOauthToken token, String statDate, int page) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_LIST;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", " application/json");
            headers.put("Access-Token", token.getAccessToken());

            //传参
            JSONObject param = new JSONObject();
            param.put("advertiser_id", token.getAccountId());
            if (!Check.isNull(statDate)) {
                param.put("startDate", DateUtils.formatDate(statDate));
                param.put("endDate", DateUtils.formatDate(statDate));
            }
            param.put("page_size", 500);
            param.put("page", page);
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            if (null == code || code != 0) {
                log.error("获取快手图片列表数据异常:{},accountId:{}", message, token.getAccountId());
                return;
            }
            JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
            if (null == details || details.size() <= 0) {
                log.info("快手图片列表信息为空=》accountId:{}", token.getAccountId());
                return;
            }
            List<KuaiShouImageGet> imageGets = new ArrayList<>();
            for (int i = 0; i < details.size(); i++) {
                var detailJson = details.getJSONObject(i);
                var kuaiShouImageGet = JSONObject.toJavaObject(detailJson, KuaiShouImageGet.class);

                if (StringUtils.isBlank(String.valueOf(kuaiShouImageGet.getImageToken()))) {
                    continue;
                }
                kuaiShouImageGet.setId(token.getAccountId() + kuaiShouImageGet.getImageToken());
                kuaiShouImageGet.setAccountId(token.getAccountId());

                Map<String, Integer> typeBySize = MaterialEnum.getTypeBySize(kuaiShouImageGet.getWidth(), kuaiShouImageGet.getHeight());
                if (!Check.isNullMap(typeBySize)) {
                    kuaiShouImageGet.setMaterialType(typeBySize.get("type"));
                }
                kuaiShouImageGet.setStatDate(DateUtils.parseDate(statDate, "yyyy-MM-dd"));

                kuaiShouImageGet.setCreateTime(new Date());
                kuaiShouImageGet.setUpdateTime(new Date());
                imageGets.add(kuaiShouImageGet);
            }
            if (!Check.isNull(imageGets) && !imageGets.isEmpty()) {
                kuaiShouImageGetService.replaceBatch(imageGets);
            }
            getImageList(token, statDate, page + 1);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }


    /**
     * 获取账户余额
     *
     * @param oauthToken
     * @return
     */
    @Override
    public JSONObject fundGet(CtopOauthToken oauthToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.FUND_GET;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", oauthToken.getAccessToken());
            headers.put("Content-Type", " application/json");
            JSONObject json = new JSONObject();
            json.put("advertiser_id", oauthToken.getAccountId());
            String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        return dataJson;
                    }

                } else {
                    log.error("获取账户余额失败，" + resultJson.getString("message"));
                }
            } else {
                log.error("获取账户余额返回为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 获取账户流水数据
     *
     * @param token
     */


    @Override
    public void getDailyFlows(CtopOauthToken token) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.DAILY_FLOWS;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", token.getAccessToken());
            headers.put("Content-Type", " application/json");
            JSONObject json = new JSONObject();
            json.put("advertiser_id", token.getAccountId());


            String endDate = DateUtils.getNowDate("yyyy-MM-dd");
            String startDate = DateUtils.getAnotherDay("yyyy-MM-dd", endDate, -2);
            json.put("start_date", startDate);
            json.put("end_date", endDate);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray details = dataJson.getJSONArray("details");
                        if (!Check.isNull(details)) {
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject detailJson = details.getJSONObject(i);
                                if (!Check.isNull(detailJson)) {
                                    String date = detailJson.getString("date");
                                    Map<String, Object> deleteMap = new HashMap<>();
                                    deleteMap.put("date", date);
                                    deleteMap.put("account_id", token.getAccountId());
                                    kuaiShouDailyFlowsService.removeByMap(deleteMap);
                                    KuaiShouDailyFlows dailyFlows = new KuaiShouDailyFlows();
                                    dailyFlows.setAccountId(token.getAccountId());
                                    dailyFlows.setDate(date);
                                    dailyFlows.setBalance(detailJson.getBigDecimal("balance"));
                                    dailyFlows.setDailyCharge(detailJson.getBigDecimal("daily_charge"));
                                    dailyFlows.setRealCharged(detailJson.getBigDecimal("real_charged"));
                                    dailyFlows.setContractRebateRealCharged(detailJson.getBigDecimal("contract_rebate_real_charged"));
                                    dailyFlows.setDirectRebateRealCharged(detailJson.getBigDecimal("direct_rebate_real_charged"));
                                    dailyFlows.setDailyTransferIn(detailJson.getBigDecimal("daily_transfer_in"));
                                    dailyFlows.setContractRebateRealRecharged(detailJson.getBigDecimal("contract_rebate_real_recharged"));
                                    dailyFlows.setDirectRebateRealRecharged(detailJson.getBigDecimal("direct_rebate_real_recharged"));
                                    dailyFlows.setDailyTransferOut(detailJson.getBigDecimal("daily_transfer_out"));
                                    dailyFlows.setRealRecharged(detailJson.getBigDecimal("real_recharged"));
                                    kuaiShouDailyFlowsService.save(dailyFlows);
                                }
                            }
                        }
                    }

                } else {
                    log.error("获取账户余额失败");
                }
            } else {
                log.error("获取账户余额返回为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取人群包接口
     *
     * @param accountId
     * @param accessToken
     * @return
     */


    @Override
    public void getPopulationList(Long accountId, String accessToken, Integer page) {
        try {
            log.info("获取人群包列表，accountId:{}", accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.POPULATION_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("status", 4);
            requestJson.put("page", page);
            requestJson.put("page_size", 500);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataDetailJson = resultJson.getJSONObject("data");
                    if (Check.isNull(dataDetailJson)) {
                        return;
                    }
                    JSONArray details = dataDetailJson.getJSONArray("details");
                    if (Check.isNull(details)) {
                        return;
                    }

                    List<KuaishouPopulation> addList = new ArrayList<>();
                    for (int i = 0; i < details.size(); i++) {
                        JSONObject dataJson = details.getJSONObject(i);
                        if (!Check.isNull(dataJson)) {
                            KuaishouPopulation population = new KuaishouPopulation();
                            population.setOrientationId(dataJson.getLong("orientation_id"));
                            population.setOrientationName(dataJson.getString("orientation_name"));
                            population.setType(dataJson.getInteger("type"));
                            population.setPopulationType(dataJson.getInteger("population_type"));
                            population.setRecordSize(dataJson.getLong("record_size"));
                            population.setMatchSize(dataJson.getLong("match_size"));
                            population.setCoverNum(dataJson.getLong("cover_num"));
                            population.setStatus(dataJson.getInteger("status"));
                            population.setPutTime(dataJson.getDate("create_time"));
                            population.setThirdPlatformCode(dataJson.getLong("third_platform_code"));
                            population.setAccountId(accountId);
                            addList.add(population);
                            // populationService.save(population);

                        }
                    }
                    if (!Check.isNull(addList)) {
                        populationService.replaceBatch(addList);
                    }
                    //   getPopulationList(accountId, accessToken, page + 1);
                } else {
                    log.error("获取人群包管理返回数据为空，accountId:{}", accountId);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 获取联盟定向媒体包列表
     *
     * @param accountId
     * @param accessToken
     * @return
     */
    @Override
    public void getMediaList(Long accountId, String accessToken, Integer page) {
        List<JSONObject> list = new ArrayList<>();
        try {
            log.info("获取人群包列表，accountId:{}", accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.MEDIA_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("page", page);
            requestJson.put("page_size", 50);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataDetailJson = resultJson.getJSONObject("data");
                    if (Check.isNull(dataDetailJson)) {
                        return;
                    }
                    JSONArray details = dataDetailJson.getJSONArray("details");
                    if (Check.isNull(details)) {
                        return;
                    }
                    for (int i = 0; i < details.size(); i++) {
                        JSONObject jsonObject = details.getJSONObject(i);
                        JSONObject media = jsonObject.getJSONObject("media");
                        if (!Check.isNull(media)) {
                            media.put("posIds", media.getString("posIds"));
                            media.put("accountId", accountId);
                            list.add(media);
                        }
                    }
                    if (!list.isEmpty()) {
                        populationService.replaceBatchMedia(list);
                    }
                    if (list.size() >= 50) {
                        getMediaList(accountId, accessToken, page + 1);
                    }
                } else {
                    log.error("获取联盟定向媒体包列表失败，accountId:{}，返回：{}", accountId, resultJson);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<JSONObject> getMedias(Long accountId) {
        return populationService.getMedias(accountId);
    }

    /**
     * 获取定向标签
     *
     * @param accountId
     * @param accessToken
     */


    @Override
    public void getTargetingTags(Long accountId, String accessToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TARGETING_TAGS;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            JSONArray typeArr = new JSONArray();
            typeArr.add("BUSINESS_INTEREST");
            typeArr.add("APP_INTEREST");
            typeArr.add("FANS_STAR");
            typeArr.add("INTEREST_VIDEO");
            for (int i = 0; i < typeArr.size(); i++) {
                String type = typeArr.get(i).toString();
                requestJson.put("type", type);
                String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (!Check.isNull(resultJson)) {
                    Integer code = resultJson.getInteger("code");
                    if (code == 0) {
                        JSONArray dataArr = resultJson.getJSONArray("data");
                        if (!Check.isNull(dataArr)) {
                            Map<String, Object> deleteMap = new HashMap<>();
                            deleteMap.put("tag_type", type);
                            targetingTagsMapper.deleteByMap(deleteMap);
                            for (int j = 0; j < dataArr.size(); j++) {
                                JSONObject dataJson = dataArr.getJSONObject(j);
                                if (!Check.isNull(dataJson)) {
                                    KuaiShouTargetingTags targetingTags = new KuaiShouTargetingTags();
                                    targetingTags.setTagId(dataJson.getLong("id"));
                                    targetingTags.setTagName(dataJson.getString("name"));
                                    targetingTags.setTagType(type);
                                    targetingTagsMapper.insert(targetingTags);
                                }
                            }
                        }
                    } else {
                        log.error("获取定向标签返回数据为空，accountId:{}", accountId);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取可选的应用定向
     *
     * @param accountId
     * @param accessToken
     * @param appName
     * @return
     */

    @Override
    public JSONArray getAppSearch(Long accountId, String accessToken, String appName) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_SEARCH;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("app_name", appName);

            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONArray returnArr = new JSONArray();
                    JSONArray data = resultJson.getJSONArray("data");
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject jsonObject = data.getJSONObject(i);
                        if (!Check.isNull(jsonObject)) {
                            JSONObject returnJson = new JSONObject();
                            returnJson.put("appId", jsonObject.getString("app_id"));
                            returnJson.put("appName", jsonObject.getString("app_name"));
                            returnArr.add(returnJson);
                        }
                    }
                    return returnArr;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取素造数据
     *
     * @param token
     * @param accountId
     * @param page
     */
    @Autowired
    private IKuaiShouVideoGetService videoGetService;
    static ExecutorService suZhaoService = Executors.newFixedThreadPool(15);

   /* @Override
    public void getSuZaoList(String token, Long accountId, int page, String startDate, String endDate) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/v1/ad_creator/video/list";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("advertiser_id", accountId);
        param.put("page", page);
        param.put("page_size", 200);
        if (!Check.isNull(startDate) && !Check.isNull(endDate)) {
            param.put("start_date", startDate);
            param.put("end_date", endDate);
        }
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        System.err.println(resultJson);
        if (Check.isNull(resultJson)) {
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手素造列表数据异常:{},accountId:{}", message, accountId);
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            return;
        }


        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }

        List<KuaiShouVideoGet> videoGetList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            if (Check.isNull(detailJson)) {
                continue;
            }
            KuaiShouVideoGet videoGet = new KuaiShouVideoGet();
            String photo_id = detailJson.getString("photo_id");
            videoGet.setId(accountId + photo_id);
            videoGet.setAccountId(accountId);
            videoGet.setCoverUrl(detailJson.getString("cover_url"));
            videoGet.setPhotoId(photo_id);
            videoGet.setPhotoName(detailJson.getString("photo_name"));
            videoGet.setStatDate(detailJson.getDate("upload_time"));
            String signature = detailJson.getString("signature");
            videoGet.setSignature(signature);
            Integer source = detailJson.getInteger("source");
            if (source == 2) {
                videoGet.setChannelType(1);
            } else {
                videoGet.setChannelType(0);
            }
            Integer new_status = detailJson.getInteger("new_status");
            if (new_status == 1) {
                videoGet.setStatus(0);
            } else {
                videoGet.setStatus(1);
            }
            videoGet.setUrl(detailJson.getString("url"));
            Integer width = detailJson.getInteger("width");
            videoGet.setWidth(width);
            Integer height = detailJson.getInteger("height");
            videoGet.setHeight(height);
            Integer type = MaterialEnum.getTypeBySize(width, height);
            if (!Check.isNull(type)) {
                videoGet.setMaterialType(type);
            }
            videoGetList.add(videoGet);
            Thread thread = new Thread() {
                @Override
                public void run() {
                    videoGetService.getKeyFrame(token, accountId, signature, photo_id);
                }
            };
            thread.start();
        }
        if (!Check.isNull(videoGetList)) {
            videoGetService.replaceBatch(videoGetList);
        }

        getSuZaoList(token, accountId, page + 1, startDate, endDate);

    }*/

    @Autowired
    private IMaterialCutFrameService cutFrameService;
    private static ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public void getAsyncCreativeList(Long accountId, String accessToken, Long campaignId) {


        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", " application/json");
            headers.put("Access-Token", accessToken);
            JSONObject param = new JSONObject();
            param.put("advertiser_id", accountId);
            param.put("page_size", 200);

           /* Map<String, Object> deleteMap = new HashMap<>();
            deleteMap.put("account_id", accountId);
            deleteMap.put("campaign_id", campaignId);
            creativeService.removeByMap(deleteMap);*/
            QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.eq("account_id", accountId);
            groupQueryWrapper.eq("campaign_id", campaignId);
            List<KuaiShouGroup> list = kuaiShouGroupService.list(groupQueryWrapper);
            if (!Check.isNull(list)) {
                for (KuaiShouGroup group : list) {
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            param.put("unit_id", group.getUnitId());
                            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
                            JSONObject resultJson = JSONObject.parseObject(result);
                            if (Check.isNull(resultJson)) {
                                log.error("获取广告创意返回结果为空,advertiserId:{}", accountId);
                                return;
                            }
                            Integer code = resultJson.getInteger("code");
                            String message = resultJson.getString("message");
                            if (null == code || code != 0) {
                                log.error("获取广告创意返回结果异常,advertiserId:{},message:{}", accountId, message);
                                return;
                            }
                            JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
                            if (null == details || details.size() <= 0) {
                                return;
                            }
                            List<KuaiShouCreative> creatives = new ArrayList<>();
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject detailJson = JSONObject.parseObject(details.get(i).toString());
                                if (!Check.isNull(detailJson)) {
                                    KuaiShouCreative creative = new KuaiShouCreative();
                                    creative.setId("" + accountId + detailJson.getLong("creative_id"));
                                    creative.setAccountId(accountId);
                                    creative.setCampaignId(detailJson.getLong("campaign_id"));
                                    creative.setUnitId(detailJson.getLong("unit_id"));
                                    creative.setCreativeId(detailJson.getLong("creative_id"));
                                    creative.setCreativeName(detailJson.getString("creative_name"));
                                    creative.setCreativeMaterialType(detailJson.getInteger("creative_material_type"));
                                    if (!Check.isNull(detailJson.getJSONArray("material_url"))) {
                                        creative.setMaterialUrl(detailJson.getJSONArray("material_url").toJSONString());
                                    }

                                    if (!Check.isNull(detailJson.getJSONArray("image_tokens"))) {
                                        creative.setImageTokens(detailJson.getJSONArray("image_tokens").toJSONString());
                                    }

                                    creative.setCreativeCategory(detailJson.getInteger("creative_category"));
                                    if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                                        creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                                    }

                                    creative.setStatus(detailJson.getInteger("status"));
                                    creative.setPutStatus(detailJson.getInteger("put_status"));
                                    creative.setCreateChannel(detailJson.getInteger("create_channel"));
                                    creative.setReviewDetail(detailJson.getString("review_detail"));
                                    creative.setCoverUrl(detailJson.getString("cover_url"));
                                    creative.setImageToken(detailJson.getString("image_token"));
                                    creative.setCoverWidth(detailJson.getString("cover_width"));
                                    creative.setCoverHeight(detailJson.getString("cover_height"));
                                    creative.setOverlayBgUrl(detailJson.getString("overlay_bg_url"));
                                    creative.setOverlayBgImageToken(detailJson.getString("overlay_bg_image_token"));
                                    creative.setStickerTitle(detailJson.getString("sticker_title"));
                                    creative.setOverlayType(detailJson.getString("overlay_type"));
                                    creative.setClickTrackUrl(detailJson.getString("click_track_url"));
                                    creative.setImpressionUrl(detailJson.getString("impression_url"));
                                    creative.setAdPhotoPlayedT3sUrl(detailJson.getString("ad_photo_played_t3s_url"));
                                    creative.setCreativeCreateTime(detailJson.getDate("create_time"));
                                    creative.setCreativeUpdateTime(detailJson.getDate("update_time"));
                                    creative.setFirstFrameType(detailJson.getInteger("first_frame_type"));
                                    creative.setShortSlogan(detailJson.getString("short_slogan"));
                                    creative.setActionbarClickUrl(detailJson.getString("actionbar_click_url"));
                                    JSONObject displayInfoJson = detailJson.getJSONObject("display_info");
                                    if (!Check.isNull(displayInfoJson)) {
                                        creative.setDescription(displayInfoJson.getString("description"));
                                        creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                                    }
                                    creative.setCreateTime(new Date());
                                    creative.setUpdateTime(new Date());
                                    creative.setSiteId(detailJson.getLong("site_id"));
                                    creative.setPhotoId(detailJson.getString("photo_id"));
                                    if (detailJson.getLong("photo_id") == 0) {
                                        JSONArray photoIds = new JSONArray();
                                        JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                                        if (!Check.isNull(programmed_creative_material)) {
                                            creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                                            JSONArray materials = programmed_creative_material.getJSONArray("materials");
                                            if (!Check.isNull(materials)) {
                                                for (int j = 0; j < materials.size(); j++) {
                                                    JSONObject materialJson = materials.getJSONObject(j);
                                                    if (!Check.isNull(materialJson)) {
                                                        Long photo_id = materialJson.getLong("photo_id");
                                                        photoIds.add(String.valueOf(photo_id));
                                                    }
                                                }
                                                creative.setPhotoIds(photoIds.toJSONString());
                                            }
                                        }
                                    }
                                    creatives.add(creative);
                                }

                            }
                            creativeService.replaceBatch(creatives);
                        }
                    });
                }

            }


        } catch (Exception e) {
            e.printStackTrace();

        }


    }

    /**
     * 获取转化目标
     *
     * @param accountId
     * @param accessToken
     * @param type
     * @return
     */
    @Override
    public List<ConvertVo> getConvertList(Long accountId, String accessToken, Integer type) {
        List<ConvertVo> convertVoList = new ArrayList<>();
        try {
            log.info("获取转化目标:accountId:{}", accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CONVERT_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("type", type);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                JSONObject data = resultJson.getJSONObject("data");
                if (!Check.isNull(data)) {
                    JSONArray details = data.getJSONArray("details");
                    if (!Check.isNull(details)) {
                        for (int i = 0; i < details.size(); i++) {
                            ConvertVo convertVo = JsonUtil.jsonToObj(details.getJSONObject(i), ConvertVo.class);
                            convertVoList.add(convertVo);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return convertVoList;
    }

    @Override
    public JSONArray getCreativeWord(Long accountId, String accessToken) {

        try {
            log.info("获取动态词包:accountId:{}", accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CREATIVE_WORD;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                return resultJson.getJSONArray("data");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 下载页
     *
     * @param accountId
     * @param appId
     * @param viewComp
     * @return
     */
    @Override
    public JSONArray getPageList(Long accountId, String token, Long appId, String viewComp) {
        JSONArray returnArr = new JSONArray();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PAGE_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            Map<String, Object> param = new HashMap<>();
          /*  JSONArray viewComps = new JSONArray();
            viewComps.add(viewComp);*/
            param.put("advertiser_id", accountId);
            param.put("page_size", 500);
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSON.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        JSONArray details = dataJson.getJSONArray("details");
                        if (!Check.isNull(details)) {
                            for (int i = 0; i < details.size(); i++) {
                                JSONObject jsonObject = details.getJSONObject(i);
                                if (!Check.isNull(jsonObject)) {
                                    JSONArray compsArr = jsonObject.getJSONArray("comps");
                                    if (!Check.isNull(compsArr)) {
                                        for (int j = 0; j < compsArr.size(); j++) {
                                            JSONObject compJson = compsArr.getJSONObject(j);
                                            if (!Check.isNull(compJson)) {
                                                JSONObject props = compJson.getJSONObject("props");
                                                if (!Check.isNull(props)) {
                                                    Long returnAppId = props.getLong("appId");
                                                    if (!Check.isNull(returnAppId)) {
                                                        if (returnAppId.equals(appId)) {
                                                            JSONObject returnJson = new JSONObject();
                                                            returnJson.put("siteId", jsonObject.getString("id"));
                                                            returnJson.put("name", jsonObject.getString("name"));
                                                            returnJson.put("appId", returnAppId);
                                                            returnArr.add(returnJson);
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return returnArr;
    }

    /**
     * 获取应用列表(新)
     *
     * @param advertiserId
     * @param accessToken
     */
    @Override
    public void getAppList(Long advertiserId, String accessToken) {
        Integer pageSize = 100;
        Integer page = 1;
        getAppList2ByPage(advertiserId, accessToken, page, pageSize);
    }

    private void getAppList2ByPage(Long advertiserId, String accessToken, Integer page, Integer pageSize) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_LIST_v2;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            JSONObject json = new JSONObject();
            json.put("advertiser_id", advertiserId);
            json.put("page", page);
            json.put("page_size", pageSize);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (Check.isNull(data)) {
                        return;
                    }
                    JSONArray dataArr = data.getJSONArray("details");
                    if (Check.isNull(dataArr)) {
                        return;
                    }
                    List<KuaiShouAppList> addList = new ArrayList<>();
                    for (int i = 0; i < dataArr.size(); i++) {
                        JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                        if (!Check.isNull(dataJson)) {
                            KuaiShouAppList appList = new KuaiShouAppList();
                            appList.setAccountId(advertiserId);
                            appList.setPlatform(dataJson.getInteger("platform"));
                            appList.setUrl(dataJson.getString("url"));
                            appList.setAppId(dataJson.getLong("app_id"));
                            appList.setAppVersion(dataJson.getString("app_version"));
                            appList.setAppName(dataJson.getString("app_name"));
                            appList.setAppIconUrl(dataJson.getString("app_icon_url"));
                            appList.setImageToken(dataJson.getString("image_token"));
                            appList.setPackageName(dataJson.getString("package_name"));
                            appList.setReturnTime(dataJson.getString("update_time"));

                            appList.setAppPrivacyUrl(dataJson.getString("app_privacy_url"));
                            addList.add(appList);
                        }
                    }
                    appListMapper.replaceBatch(addList);
                    getAppList2ByPage(advertiserId, accessToken, page + 1, pageSize);
                } else {
                    log.error("获取应用列表失败，返回信息：{}", resultJson);
                }
            } else {
                log.error("获取地域列表返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public JSONArray getAppNames(Long accountId, String accessToken, JSONArray appIds) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_NAME;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject json = new JSONObject();
        json.put("advertiser_id", accountId);
        json.put("type", 1);
        json.put("ids", appIds);
        String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            Integer code = resultJson.getInteger("code");
            if (code == 0) {
                JSONObject data = resultJson.getJSONObject("data");
                if (!Check.isNull(data)) {
                    JSONArray keyword = data.getJSONArray("keyword");
                    if (!Check.isNull(keyword)) {
                        return keyword;

                    }
                }
            }

        }
        return new JSONArray();

    }

    @Override
    public JSONObject mcbConversionInfos(Long accountId, String accessToken, Integer sceneCategory, Integer campaignType, JSONArray sceneIds, Long appId) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/v1/ocpc/mcb/ocpx_types";
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (!Check.isNull(campaignType)) {
            param.put("campaign_type", campaignType);
        }
        if (!Check.isNull(appId)) {
            param.put("app_id", appId);
        }
        if (!Check.isNull(sceneCategory)) {
            param.put("scene_category", sceneCategory);
        }

        if (!Check.isNull(sceneIds)) {
            param.put("scene_ids", sceneIds);
        }
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject returnJson = new JSONObject();
        try {
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            returnJson = JSONObject.parseObject(result);
            if (Check.isNull(returnJson)) {
                returnJson.put("code", -1);
                returnJson.put("message", "返回信息为空");
            }

        } catch (Exception e) {
            returnJson.put("code", -1);
            returnJson.put("message", "系统错误");

        }
        return returnJson;
    }

}
