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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxl.job.executor.batch.entity.*;
import com.xxl.job.executor.batch.mapper.*;
import com.xxl.job.executor.batch.service.*;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.constant.KuaishouInterfaceConstant;
import com.xxl.job.executor.constant.MaterialEnum;
import com.xxl.job.executor.material.entity.KuaishouResult;
import com.xxl.job.executor.material.entity.KuaishouResultToken;
import com.xxl.job.executor.report.entity.*;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyAccountMapper;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyCampaignMapper;
import com.xxl.job.executor.report.mapper.KuaishouReportDailyGroupMapper;
import com.xxl.job.executor.report.service.*;
import com.xxl.job.executor.utils.Check;
import com.xxl.job.executor.utils.DateUtils;
import com.xxl.job.executor.utils.HttpUtils;
import com.xxl.job.executor.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
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.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class KuaishouInterfaceServiceImpl implements IKuaishouInterfaceService {
    @Autowired
    private KuaishouOperationRecordMapper kuaishouOperationRecordMapper;
    @Autowired
    KuaishouReportDailyCampaignMapper dailyCampaignMapper;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private KuaishouReportDailyGroupMapper dailyGroupMapper;
    @Autowired
    private KuaiShouAdvertiserBaseInfoMapper advertiserBaseInfoMapper;
    @Autowired
    private KuaishouReportDailyAccountMapper dailyAccountMapper;
    @Autowired
    private IKuaishouReportHourlyAccountService hourlyAccountService;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private IKuaiShouImageGetService iKuaiShouImageGetService;
    @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 IKuaiShouCampaignService kuaiShouCampaignService;
    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;
    @Autowired
    private IKuaiShouImageGetService kuaiShouImageGetService;
    @Autowired
    private IKuaiShouDailyFlowsService kuaiShouDailyFlowsService;
    @Autowired
    private IKuaiShouAdvertiserBaseInfoService KuaiShouAdvertiserBaseInfoService;
    @Autowired
    private IKuaiShouVideoGetService videoGetService;


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


    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", 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:{}", message, token.getAccountId());
            return;
        }
        List<KuaishouReportHourlyAccount>accounts = 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 kuaishouReportHourlyAccount = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyAccount.class);
            kuaishouReportHourlyAccount.setAccountId(token.getAccountId());
            kuaishouReportHourlyAccount.setId(token.getAccountId() + kuaishouReportHourlyAccount.getStatDate() + kuaishouReportHourlyAccount.getStatHour());
            accounts.add(kuaishouReportHourlyAccount);
        }
        hourlyAccountService.replaceBatch(accounts);
    }


    @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());
            param.put("page_size", 500);
            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;
            }
            KuaiShouAdvertiserBaseInfo baseInfo = KuaiShouAdvertiserBaseInfoService.getBaseInfo(token.getAccountId());
            Long userId = null;
            if (!Check.isNull(baseInfo)) {
                userId = Long.valueOf(baseInfo.getUserId());
            }
            for (int i = 0; i < details.size(); i++) {
                var detailJson = details.getJSONObject(i);
                Integer source = detailJson.getInteger("source");
                if (source == 2) {
                    continue;
                }
                KuaiShouVideoGet byId = kuaiShouVideoGetService.getById(token.getAccountId() + detailJson.getString("photo_id"));
                if (!Check.isNull(byId)) {
                    continue;
                }
                var kuaiShouVideoGet = JSONObject.toJavaObject(detailJson, KuaiShouVideoGet.class);
                kuaiShouVideoGet.setId(token.getAccountId() + kuaiShouVideoGet.getPhotoId());

                kuaiShouVideoGet.setAccountId(token.getAccountId());
                kuaiShouVideoGet.setStatDate(detailJson.getDate("upload_time"));
                Integer type = MaterialEnum.getTypeBySize(kuaiShouVideoGet.getWidth(), kuaiShouVideoGet.getHeight());
                if (!Check.isNull(type)) {
                    kuaiShouVideoGet.setMaterialType(type);
                }

                kuaiShouVideoGet.setUserId(userId);
                kuaiShouVideoGetService.saveOrUpdate(kuaiShouVideoGet);

                //TODO 需要独立抽取抽帧任务
//                Thread thread = new Thread() {
//                    @Override
//                    public void run() {
//                        videoGetService.getKeyFrame(token.getAccessToken(), token.getAccountId(), kuaiShouVideoGet.getSignature(), kuaiShouVideoGet.getPhotoId());
//                    }
//                };
//                thread.start();

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

    }


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


    private void getAccountDailyReportByPage(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("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;
        }

        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"));
                var KuaishouReportDailyAccount = JSONObject.toJavaObject(detailJson, KuaishouReportDailyAccount.class);
                KuaishouReportDailyAccount.setAccountId(token.getAccountId());
                dailyAccountMapper.insertSelective(KuaishouReportDailyAccount);
            }
        }
        getAccountDailyReportByPage(token, startDate, endDate, page + 1);
    }


    @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");
        Long totalCount = resultJson.getJSONObject("data").getLong("total_count");
        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());
            campaigns.add(hourlyCampaign);
        }
        hourlyCampaignService.replaceBatch(campaigns);
        if(totalCount>page*2000){
            getAdvertiserReportHourlyByPage(token, startDate, endDate, page + 1);
        }else {
            log.info("快手广告计划时报表信息完成=》accountId:{}", token.getAccountId());
        }
    }


    @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 void getAdvertiserGroupReportDaily(CtopOauthToken token, Date startDate, Date endDate) {
        getAdvertiserGroupReportDailyByPage(token, startDate, endDate, 1);
    }

    private void getAdvertiserGroupReportDailyByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        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", 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.isEmpty()) {
            log.info("快手广告组报表信息获取完成=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportDailyGroup>groups = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            var detailJson = details.getJSONObject(i);
            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"));

            var dailyGroup = JSONObject.toJavaObject(detailJson, KuaishouReportDailyGroup.class);
            dailyGroup.setAccountId(token.getAccountId());
            groups.add(dailyGroup);
        }
        dailyGroupMapper.replaceBatch(groups);
        getAdvertiserGroupReportDailyByPage(token, startDate, endDate, page + 1);
    }

    @Override
    public KuaishouResult<KuaishouReportDailyGroup> getGroupDailyReport(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", "DAILY");
        param.put("page_size", pageSize);
        param.put("page", pageNum);
        KuaishouResult<KuaishouReportDailyGroup> 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<KuaishouReportDailyGroup>>() {
            });
            List<KuaishouReportDailyGroup> dailyGroups = kuaishouResult.getData().getDetails();
            dailyGroups.forEach((dailyGroup) -> {
                dailyGroup.setAccountId(advertiserId);
                dailyGroupMapper.insertSelective(dailyGroup);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return kuaishouResult;
    }

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

    private void getGroupHourlyReportByPage(CtopOauthToken token, Date startDate, Date endDate, int page) {
        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", 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");
        Long totalCount = resultJson.getJSONObject("data").getLong("total_count");
        if (null == details || details.size() <= 0) {
            log.info("快手广告组时报表信息完成=》accountId:{}", token.getAccountId());
            return;
        }
        List<KuaishouReportHourlyGroup> groups = 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 hourlyGroup = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyGroup.class);
            hourlyGroup.setAccountId(token.getAccountId());
            hourlyGroup.setId(hourlyGroup.getAccountId() + hourlyGroup.getUnitId() + hourlyGroup.getStatDate() + hourlyGroup.getStatHour());
            hourlyGroup.setCreateTime(new Date());
            hourlyGroup.setUpdateTime(new Date());
            groups.add(hourlyGroup);
        }
        hourlyGroupService.replaceBatch(groups);
        if(totalCount>page*2000){
            getGroupHourlyReportByPage(token, startDate, endDate, page + 1);
        }else{
            log.info("快手广告组时报表信息完成=》accountId:{}", token.getAccountId());
        }
    }

    @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<>();
        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(campaignIds)) {
            param.put("campaign_ids", campaignIds);
        }
        if (!Check.isNull(creativeIds)) {
            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;
        }
        List<KuaishouReportDailyCreative>creatives = 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 creative = JSONObject.toJavaObject(detailJson, KuaishouReportDailyCreative.class);
            creative.setAccountId(token.getAccountId());
            creative.setSignature("-");
            creatives.add(creative);
        }
        if(!creatives.isEmpty()){
            dailyCreativeService.replaceBatch(creatives);
        }
        getAdvertiserCreativeReportDailyByPage(token, startDate, endDate, campaignIds, creativeIds, page + 1);
    }

    @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");
        Long totalCount = resultJson.getJSONObject("data").getLong("total_count");
        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);
        if(totalCount>page*2000){
            getAdvertiserCreativeReportHourlyByPage(token, startDate, endDate, page + 1);
        }else{
            log.info("快手广告创意时报表信息完成=》accountId:{}", token.getAccountId());
        }
    }

    @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 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", 200);

        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);
    }


    /**
     * 获取 单条 广告计划数据
     *
     * @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"));

                campaigns.add(campaign);
            }
        }
        kuaiShouCampaignService.replaceBatch(campaigns);
    }

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


    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);
        getGroupListByPage(token, startDate, endDate, page + 1);
    }

    private void addGroup(Long advertiserId, JSONArray details) {
        if (!Check.isNull(details)) {
            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 bid_type = detail.getInteger("bid_type");
                    Long bid = detail.getLong("bid");
                    Long cpa_bid = detail.getLong("cpa_bid");
                    Long day_budget = detail.getLong("day_budget");
                    Integer ocpx_action_type = detail.getInteger("ocpx_action_type");
                    Long unitId = detail.getLong("unit_id");
                    String unit_name = detail.getString("unit_name");
                    Integer status = detail.getInteger("status");
                    Integer put_status = detail.getInteger("put_status");

                    KuaiShouGroup group = new KuaiShouGroup();
                    group.setId("" + advertiserId + unitId);
                    group.setAccountId(advertiserId);
                    group.setCampaignId(detail.getLong("campaign_id"));
                    group.setUnitId(unitId);
                    group.setUnitName(unit_name);
                    group.setStatus(status);
                    group.setPutStatus(put_status);
                    group.setCreateChannel(detail.getInteger("create_channel"));
                    group.setReviewDetail(detail.getString("review_detail"));
                    group.setBidType(bid_type);
                    group.setBid(bid);
                    group.setCpaBid(cpa_bid);
                    group.setOcpxActionType(ocpx_action_type);
                    group.setDeepConversionType(detail.getInteger("deep_conversion_type"));
                    group.setDeepConversionBid(detail.getLong("deep_conversion_bid"));
                    group.setDayBudget(day_budget);
                    group.setSpeed(detail.getInteger("speed"));
                    group.setBeginTime(detail.getString("begin_time"));
                    group.setEndTime(detail.getString("end_time"));
                    group.setScheduleTime(detail.getString("schedule_time"));
                    group.setSceneId(detail.getJSONArray("scene_id") + "");
                    group.setShowMode(detail.getInteger("show_mode"));
                    group.setUnitType(detail.getInteger("unit_type"));
                    group.setUrlType(detail.getInteger("url_type"));
                    group.setUrl(detail.getString("url"));
                    group.setAppId(detail.getLong("app_id"));
                    group.setAppIconUrl(detail.getString("app_icon_url"));
                    group.setGroupCreateTime(detail.getString("create_time"));
                    group.setGroupUpdateTime(detail.getString("update_time"));
                    group.setConvertId(detail.getLong("convert_id"));
                    group.setUseAppMarket(detail.getInteger("use_app_market"));
                    group.setAppStore(detail.getJSONArray("app_store") + "");
                    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 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 dataArray = resultJson.getJSONArray("data");
                    if (!Check.isNull(dataArray)) {
                        KuaiShouAdvertiserBaseInfo baseInfo = KuaiShouAdvertiserBaseInfoService.getBaseInfo(accountId);
                        Long userId = null;
                        if (!Check.isNull(baseInfo)) {
                            userId = Long.valueOf(baseInfo.getUserId());
                        }
                        for (int i = 0; i < dataArray.size(); i++) {
                            JSONObject detailJson = dataArray.getJSONObject(i);
                            if (!Check.isNull(detailJson)) {

                                KuaiShouVideoGet byId = kuaiShouVideoGetService.getById(accountId + photoId);
                                if (!Check.isNull(byId)) {
                                    continue;
                                }
                                var kuaiShouVideoGet = JSONObject.toJavaObject(detailJson, KuaiShouVideoGet.class);
                                kuaiShouVideoGet.setId(accountId + photoId);

                                kuaiShouVideoGet.setAccountId(accountId);
                                kuaiShouVideoGet.setStatDate(detailJson.getDate("upload_time"));
                                kuaiShouVideoGet.setUpdateTime(new Date());
                                Integer type = MaterialEnum.getTypeBySize(kuaiShouVideoGet.getWidth(), kuaiShouVideoGet.getHeight());
                                if (!Check.isNull(type)) {
                                    kuaiShouVideoGet.setMaterialType(type);
                                }

                                kuaiShouVideoGet.setUserId(userId);
                                kuaiShouVideoGetService.saveOrUpdate(kuaiShouVideoGet);

                                Thread thread = new Thread() {
                                    @Override
                                    public void run() {
                                        videoGetService.getKeyFrame(accessToken, accountId, kuaiShouVideoGet.getSignature(), kuaiShouVideoGet.getPhotoId());
                                    }
                                };
                                thread.start();
                            }
                        }
                    }
                } 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);
        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();
        }
    }

    @Override
    public void getOperationRecord(Long advertiserId, String accessToken, Integer operationTarget, String startDate, String endDate){
        getOperationRecordByPage(advertiserId, accessToken,1, 500, operationTarget, startDate, endDate);
    }

    private void getOperationRecordByPage(Long advertiserId, String accessToken, Integer page, Integer pageSize, Integer operationTarget, String startDate, String endDate) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.OPERATION_RECORD;
        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("operation_target", operationTarget);
        json.put("page", page);
        json.put("page_size", pageSize);
        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 data = resultJson.getJSONObject("data");
                if (!Check.isNull(data)) {
                    List<KuaishouOperationRecord> recordList =  new ArrayList();

                    Integer totalCount = data.getInteger("total_count");
                    JSONArray dataArr = data.getJSONArray("details");
                    for (int i = 0; i < dataArr.size(); i++) {
                        JSONObject dataJson = JSONObject.parseObject(dataArr.get(i).toString());
                        if (!Check.isNull(dataJson)) {
                            Date operationTime = dataJson.getDate("operation_time");
                            Integer operationType = dataJson.getInteger("operation_type");
                            operationTarget = dataJson.getInteger("operation_target");
                            Integer roleType = dataJson.getInteger("role_type");
                            String objectId = dataJson.getString("object_id");
                            String objectName = dataJson.getString("object_name");

                            String contentLogArrayString =  dataJson.getString("content_log");
                            KuaishouOperationRecord record = new KuaishouOperationRecord();
                            record.setAccountId(advertiserId);
                            record.setStatDate(DateUtils.formatDate(operationTime));
                            record.setOperationTime(operationTime);
                            record.setOperationType(operationType);
                            record.setRoleType(roleType);
                            record.setObjectName(objectName);
                            record.setOperationTarget(operationTarget);
                            record.setObjectId(objectId);
                            record.setLog(contentLogArrayString);
                            recordList.add(record);
                        }
                    }
                    if(recordList.size()!=0){
                        operationRecordInsert(recordList,operationTarget);
                    }

                    Integer totalPage = (totalCount - 1) / pageSize + 1;
                    if (page < totalPage) {
                        getOperationRecordByPage(advertiserId, accessToken, page + 1, pageSize, operationTarget, startDate, endDate);
                    }
                }else{
                    log.error("快手操作记录接口data结果不正确，{} ~ {}, resultJson:{}", startDate, endDate, result);
                }
            }else{
                log.error("快手操作记录接口code返回结果不正确，{} ~ {}, resultJson:{}", startDate, endDate, result);
            }
        } else {
            log.error("快手操作记录接口获取地域列表返回结果为空，{} ~ {}, resultJson:{}", startDate, endDate, result);
        }

    }

    private void operationRecordDelete(KuaishouOperationRecord recordDelete, Integer operationTarget){
        if(operationTarget == 1){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoAccount(recordDelete);
        }else if(operationTarget == 2){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoCampaign(recordDelete);
        }else if(operationTarget == 3){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoUnit(recordDelete);
        }else if(operationTarget == 4){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoCreative(recordDelete);
        }else if(operationTarget == 5){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoVideo(recordDelete);
        }else if(operationTarget == 6){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoApp(recordDelete);
        }else if(operationTarget == 7){
            kuaishouOperationRecordMapper.deleteOperationRecordInfoPackage(recordDelete);
        }
    }

    private void operationRecordInsert(List<KuaishouOperationRecord> recordList, Integer operationTarget){
        if(operationTarget == 1){
            kuaishouOperationRecordMapper.insertOperationRecordInfoAccount(recordList);
        }else if(operationTarget == 2){
            kuaishouOperationRecordMapper.insertOperationRecordInfoCampaign(recordList);
        }else if(operationTarget == 3){
            kuaishouOperationRecordMapper.insertOperationRecordInfoUnit(recordList);
        }else if(operationTarget == 4){
            kuaishouOperationRecordMapper.insertOperationRecordInfoCreative(recordList);
        }else if(operationTarget == 5){
            kuaishouOperationRecordMapper.insertOperationRecordInfoVideo(recordList);
        }else if(operationTarget == 6){
            kuaishouOperationRecordMapper.insertOperationRecordInfoApp(recordList);
        }else if(operationTarget == 7){
            kuaishouOperationRecordMapper.insertOperationRecordInfoPackage(recordList);
        }
    }

    /**
     * 获取token
     *
     * @param authCode
     * @return
     */
    @Override
    public KuaishouResultToken getAccessToken(String authCode, Integer agentType) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AUTH_TOKEN;
        JSONObject requestJson = new JSONObject();
        requestJson.put("auth_code", authCode);

        if (agentType == 1) { // 本代理商开户
            requestJson.put("app_id", PropertiesUtils.getConfig("kuaishou_appid"));
            requestJson.put("secret", PropertiesUtils.getConfig("kuaishou_secret"));
        } else if (agentType == 0) {
            requestJson.put("app_id", PropertiesUtils.getConfig("kuaishou_third_appid"));
            requestJson.put("secret", PropertiesUtils.getConfig("kuaishou_third_secret"));
        }
        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) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.DEEP_CONVERSION_INFOS;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", advertiserId);
        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"));
                        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;
    }

    /**
     * 获取视频信息
     *
     * @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"));
                                Integer type = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                                if (!Check.isNull(type)) {
                                    videoGet.setMaterialType(type);
                                }
                                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"));
                        Integer type = MaterialEnum.getTypeBySize(dataJson.getInteger("width"), dataJson.getInteger("height"));
                        if (!Check.isNull(type)) {
                            imageGet.setMaterialType(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 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 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.isEmpty()) {
                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 (Check.isNull(String.valueOf(kuaiShouImageGet.getImageToken()))) {
                    continue;
                }
                kuaiShouImageGet.setId(token.getAccountId() + kuaiShouImageGet.getImageToken());
                kuaiShouImageGet.setAccountId(token.getAccountId());
                Integer type = MaterialEnum.getTypeBySize(kuaiShouImageGet.getWidth(), kuaiShouImageGet.getHeight());
                if (!Check.isNull(type)) {
                    kuaiShouImageGet.setMaterialType(type);
                }
                kuaiShouImageGet.setStatDate(DateUtils.parseDate(statDate, "yyyy-MM-dd"));
                imageGets.add(kuaiShouImageGet);
            }
            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("获取账户余额失败");
                }
            } 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();
        }
    }

    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);
        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;
        }
        KuaiShouAdvertiserBaseInfo baseInfo = KuaiShouAdvertiserBaseInfoService.getBaseInfo(accountId);
        Long userId = null;
        if (!Check.isNull(baseInfo)) {
            userId = Long.valueOf(baseInfo.getUserId());
        }
        for (int i = 0; i < details.size(); i++) {
            JSONObject jsonObject = details.getJSONObject(i);
            if (!Check.isNull(jsonObject)) {
                KuaiShouVideoGet kuaiShouVideoGet = new KuaiShouVideoGet();
                Long photo_id = jsonObject.getLong("photo_id");
                kuaiShouVideoGet.setId(String.valueOf(accountId) + String.valueOf(photo_id));
                kuaiShouVideoGet.setPhotoId(String.valueOf(photo_id));
                kuaiShouVideoGet.setUrl(jsonObject.getString("watermark_url"));
                kuaiShouVideoGet.setWidth(jsonObject.getInteger("width"));
                kuaiShouVideoGet.setHeight(jsonObject.getInteger("height"));
                kuaiShouVideoGet.setCoverUrl(jsonObject.getString("cover_url"));
                kuaiShouVideoGet.setAccountId(accountId);
                String md5 = jsonObject.getString("md5");
                kuaiShouVideoGet.setSignature(md5);
                kuaiShouVideoGet.setStatDate(jsonObject.getDate("sync_date"));
                kuaiShouVideoGet.setChannelType(1);
                kuaiShouVideoGet.setUserId(userId);
                kuaiShouVideoGet.setMaterialId(jsonObject.getString("material_id"));
                Integer type = MaterialEnum.getTypeBySize(kuaiShouVideoGet.getWidth(), kuaiShouVideoGet.getHeight());
                if (!Check.isNull(type)) {
                    kuaiShouVideoGet.setMaterialType(type);
                }
                kuaiShouVideoGetService.saveOrUpdate(kuaiShouVideoGet);
                suZhaoService.submit(new Runnable() {
                    @Override
                    public void run() {
                        videoGetService.getKeyFrame(token, accountId, md5, String.valueOf(photo_id));
                    }
                });
            }
        }
        getSuZaoList(token, accountId, page + 1, startDate, endDate);

    }

    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);

            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();
        }
    }
}
