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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.enums.MaterialEnum;
import cn.com.ctop.common.module.mapper.MaterialInfoMapper;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.kuaishou.modules.batch.entity.*;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.ConvertVo;
import cn.com.ctop.kuaishou.modules.batch.mapper.*;
import cn.com.ctop.kuaishou.modules.batch.service.*;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResult;
import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResultToken;
import cn.com.ctop.kuaishou.modules.report.entity.*;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyAccountMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyCampaignMapper;
import cn.com.ctop.kuaishou.modules.report.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.ParseException;
import org.jeecg.common.util.DateUtils;
import org.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.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

    @Autowired
    KuaishouReportDailyCampaignMapper dailyCampaignMapper;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private KuaiShouConversionInfosMapper conversionInfosMapper;
    @Autowired
    private KuaiShouConversionTypesMapper conversionTypesMapper;
    @Autowired
    private KuaiShouVideoUploadMapper videoUploadMapper;
    @Autowired
    private KuaiShouVideoMapper kuaiShouVideoMapper;
    @Autowired
    private KuaiShouRegionListChildrenMapper regionListChildrenMapper;
    @Autowired
    private KuaiShouRegionListParentMapper regionListParentMapper;
    @Autowired
    private KuaiShouImageUploandMapper imageUploandMapper;
    @Autowired
    private KuaiShouAppCreateMapper appCreateMapper;
    @Autowired
    private KuaiShouAppListMapper appListMapper;
    @Autowired
    private RestTemplate rest;
    @Autowired
    private IKuaishouReportHourlyAccountService hourlyAccountService;
    @Autowired
    private KuaiShouAdvertiserBaseInfoMapper advertiserBaseInfoMapper;
    @Autowired
    private IKuaiShouImageGetService iKuaiShouImageGetService;
    @Autowired
    private MaterialInfoMapper materialInfoMapper;
    @Autowired
    private KuaiShouTargetingTagsMapper targetingTagsMapper;
    @Autowired
    private KuaishouReportDailyAccountMapper dailyAccountMapper;
    @Autowired
    private IKuaishouReportHourlyCampaignService hourlyCampaignService;
    @Autowired
    private IKuaishouReportDailyCampaignService dailyCampaignService;
    @Autowired
    private IKuaishouReportDailyGroupService dailyGroupService;
    @Autowired
    private IKuaishouReportHourlyGroupService hourlyGroupService;
    @Autowired
    private IKuaishouReportDailyCreativeService dailyCreativeService;
    @Autowired
    private IKuaishouReportHourlyCreativeService hourlyCreativeService;
    @Autowired
    private IKuaiShouVideoGetService kuaiShouVideoGetService;
    @Autowired
    private IKuaiShouCreativeService kuaiShouCreativeService;
    @Autowired
    private IKuaiShouCampaignService kuaiShouCampaignService;
    @Autowired
    private IKuaiShouGroupService kuaiShouGroupService;
    @Autowired
    private IUserAllocationService userAllocationService;
    @Autowired
    private IKuaishouReportDailyCreativeStatisticService dailyCreativeStatisticService;
    @Autowired
    private IKuaiShouHistoryReportTaskService historyReportTaskService;
    @Autowired
    private IKuaiShouImageGetService kuaiShouImageGetService;
    @Autowired
    private IKuaiShouDailyFlowsService kuaiShouDailyFlowsService;
    @Autowired
    private IKuaishouPopulationService populationService;
    @Autowired
    private IKuaiShouGroupService getKuaiShouGroupService;
    @Autowired
    private IKuaiShouAdvertiserBaseInfoService KuaiShouAdvertiserBaseInfoService;


    @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) {
            return;
        }
        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());
            kuaishouReportHourlyAccount.setCreateTime(new Date());
            kuaishouReportHourlyAccount.setUpdateTime(new Date());
            hourlyAccountService.saveOrUpdate(kuaishouReportHourlyAccount);
        }


    }


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

        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());
            campaign.setId("" + campaign.getAccountId() + campaign.getCampaignId() + campaign.getStatDate());
            dailyCampaignService.saveOrUpdate(campaign);
        }
        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);
                campaign.setId("" + campaign.getAccountId() + campaign.getCampaignId() + campaign.getStatDate());
                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", 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<KuaishouReportHourlyCampaign> campaigns = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var hourlyCampaign = JSONObject.toJavaObject(detailJson, KuaishouReportHourlyCampaign.class);
            hourlyCampaign.setAccountId(token.getAccountId());
            hourlyCampaign.setId("" + hourlyCampaign.getAccountId() + hourlyCampaign.getCampaignId() + hourlyCampaign.getStatDate() + hourlyCampaign.getStatHour());
            hourlyCampaign.setCreateTime(new Date());
            hourlyCampaign.setUpdateTime(new Date());
            campaigns.add(hourlyCampaign);
        }
        hourlyCampaignService.replaceBatch(campaigns);
        getAdvertiserReportHourlyByPage(token, startDate, endDate, page + 1);
    }


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


    @Override
    public 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.size() <= 0) {
            log.info("快手广告组报表信息为空=》accountId:{}", token.getAccountId());
            return;
        }
        for (int i = 0; i < details.size(); i++) {
            var detailJson = details.getJSONObject(i);
            var show = detailJson.getLong("show");
            detailJson.put("photo_show", show);
            var like = detailJson.getLong("like");
            detailJson.put("photo_like", like);
            var dailyGroup = JSONObject.toJavaObject(detailJson, KuaishouReportDailyGroup.class);
            dailyGroup.setAccountId(token.getAccountId());
            dailyGroup.setId("" + dailyGroup.getAccountId() + dailyGroup.getUnitId() + dailyGroup.getStatDate());
            dailyGroupService.saveOrUpdate(dailyGroup);
        }
        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);
                dailyGroup.setId("" + dailyGroup.getAccountId() + dailyGroup.getUnitId() + dailyGroup.getStatDate());
                dailyGroupService.saveOrUpdate(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", 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<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);


        getGroupHourlyReportByPage(token, startDate, endDate, page + 1);
    }

    @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) {
        getAdvertiserCreativeReportDailyByPage(token, startDate, endDate, campaignIds, 1);
    }

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

        }

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

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

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

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

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


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

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


    @Override
    public void loadKuaishouDataSingle(CtopOauthToken token) throws java.text.ParseException {


        Date endDate = new Date();
        for (int i = 0; i < 7; i++) {
            Date getStartDate = DateUtils.addDay(endDate, -i);
            //1: 获取广告主信息数据
            getAdvertiserReportHourly(token, getStartDate, getStartDate);
            //2：获取广告计划信息数据
            // getAdvertiserCampaignReportHourly(token, getStartDate, getStartDate);
            //3：获取广告组信息数据
            // getAdvertiserGroupReportHourly(token, getStartDate, getStartDate);
            //4: 获取广告创意信息数据
            // getAdvertiserCreativeReportHourly(token, getStartDate, getStartDate);
        }
        //获取全量广告计划数据
        getCampaignList(token, null, null);
        //获取全量广组主数据
        getGroupList(token, null, null);
        //获取全量创意数据
        getCreativeList(token, null, null);
        //获取全量视频素材数据

        //获取图片信息数据


        getAppList(token.getAccountId(), token.getAccessToken());

        log.info("----------------开始历史数据获取，accountId：{}", token.getAccountId());

        String endDateStr = DateUtils.getDate("yyyy-MM-dd");
        String startDate = DateUtils.addMonth(endDateStr, -6);

        historyReportTaskService.createTask(token.getAccountId(), token.getAccessToken(), startDate, endDateStr, CtopAdConstant.KUAISHOU_LOAD_JOB_TYPE_HISTORY);
        getVideoList(token, null, null);
        getSuZaoList(token.getAccessToken(), token.getAccountId(), 1, null, null);
        String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
        String videoEndDate = DateUtils.addDay(nowDate, -180);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date end = simpleDateFormat.parse(nowDate);
        Date start = simpleDateFormat.parse(videoEndDate);
        List<Date> dates = DateUtils.findDates(start, end);
        for (int i = 0; i < dates.size(); i++) {
            String formatDate = simpleDateFormat.format(dates.get(i));
            getImageList(token, formatDate);
        }


    }


    /**
     * 创建广告计划
     *
     * @param accessToken  token信息
     * @param advertiserId 广告主id
     * @param requestJson  请求参数拼装
     */
    @Override
    public Map<String, Object> campaignCreate(String accessToken, Long advertiserId, JSONObject requestJson) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_CREATE;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            requestJson.put("advertiser_id", advertiserId);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    Long campaignId = dataJson.getLong("campaign_id");
                    returnMap.put("code", 0);
                    returnMap.put("message", "success");
                    returnMap.put("campaignId", campaignId);
                    returnMap.put("success", true);
                    // 创建成功 拉取广告组信息
                    getCampaign(accessToken, advertiserId, campaignId);
                } else {
                    log.error("创建广告计划失败,advertiser_id:{},返回信息：{}", advertiserId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创建广告计划失败");
                    returnMap.put("success", false);
                }
            } else {
                log.error("快手创建广告计划返回内容为空,advertiser_id:{}", advertiserId);
                returnMap.put("code", -1);
                returnMap.put("message", "创建广告计划错误");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建广告计划失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "创建广告计划失败");
            returnMap.put("desc", "Interface exception");
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 创建 广告组
     *
     * @param accessToken
     * @param advertiserId
     * @param requestJson
     * @return
     */


    @Override
    public Map<String, Object> adUnitCreate(String accessToken, Long advertiserId, JSONObject requestJson, Integer count) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            if (Check.isNull(requestJson)) {
                throw new Exception("参数不能为空");
            }
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_UNIT_CREATE;
            Map<String, String> headers = new HashMap<>();
            requestJson.put("advertiser_id", advertiserId);
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("快手创建广告组返回，accountId:{},返回结果:{}", advertiserId, resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        Long unitId = dataJson.getLong("unit_id");

                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(500);
                                    getKuaiShouGroupService.getGroupByUnitId(accessToken, advertiserId, unitId);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }

                        };
                        thread.start();


                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                        returnMap.put("unitId", unitId);
                        returnMap.put("success", true);
                    }

                } else {

                    if (code == 500000 && count <= 4) {
                        adUnitCreate(accessToken, advertiserId, requestJson, count + 1);
                    }
                    log.error("创建广告信息失败,advertiser_id:{},返回信息：{}，入参：{}", advertiserId, resultJson, requestJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创建广告组失败");
                    returnMap.put("success", false);
                }
            } else {
                if (count <= 4) {
                    log.info("创建组失败，重试，入参：{}", requestJson);
                    adUnitCreate(accessToken, advertiserId, requestJson, count + 1);
                }
                log.error("快手创建广告计划返回内容为空,advertiser_id:{}，入参：{}", advertiserId, requestJson);
                returnMap.put("code", -1);
                returnMap.put("message", "创建广告组异常");
                returnMap.put("desc", "result is null");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建广告计划失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "创建广告组错误");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

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

    private void getCampaignListByPage(String accessToken, Long accountId, Date startDate, Date endDate, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.CAMPAIGN_LIST;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        headers.put("Content-Type", " application/json");
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (startDate != null && endDate != null) {
            param.put("start_date", DateUtils.formatDate(startDate));
            param.put("end_date", DateUtils.formatDate(endDate));
        }
        param.put("page", page);
        param.put("page_size", 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"));
                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", 200);
        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)) {
                    KuaiShouGroup group = new KuaiShouGroup();
                    Long unitId = detail.getLong("unit_id");
                    group.setId("" + advertiserId + unitId);
                    group.setAccountId(advertiserId);
                    group.setCampaignId(detail.getLong("campaign_id"));
                    group.setUnitId(unitId);
                    group.setUnitName(detail.getString("unit_name"));
                    group.setStatus(detail.getInteger("status"));
                    group.setPutStatus(detail.getInteger("put_status"));
                    group.setCreateChannel(detail.getInteger("create_channel"));
                    group.setReviewDetail(detail.getString("review_detail"));
                    group.setBidType(detail.getInteger("bid_type"));
                    group.setBid(detail.getLong("bid"));
                    group.setCpaBid(detail.getLong("cpa_bid"));
                    group.setOcpxActionType(detail.getInteger("ocpx_action_type"));
                    group.setDeepConversionType(detail.getInteger("deep_conversion_type"));
                    group.setDeepConversionBid(detail.getLong("deep_conversion_bid"));
                    group.setDayBudget(detail.getLong("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 {
            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", 200);
            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.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");
                                    if (!Check.isNull(displayInfoJson)) {
                                        creative.setDescription(displayInfoJson.getString("description"));
                                        creative.setActionBarText(displayInfoJson.getString("action_bar_text"));
                                    }
                                    creative.setCreateTime(new Date());
                                    creative.setUpdateTime(new Date());
                                    creative.setSiteId(detailJson.getLong("site_id"));
                                    creative.setPhotoId(detailJson.getString("photo_id"));
                                    if (detailJson.getLong("photo_id") == 0) {
                                        JSONArray photoIds = new JSONArray();
                                        JSONObject programmed_creative_material = detailJson.getJSONObject("programmed_creative_material");
                                        if (!Check.isNull(programmed_creative_material)) {
                                            creative.setProgrammedCreativeMaterial(programmed_creative_material.toJSONString());
                                            JSONArray materials = programmed_creative_material.getJSONArray("materials");
                                            if (!Check.isNull(materials)) {
                                                for (int j = 0; j < materials.size(); j++) {
                                                    JSONObject materialJson = materials.getJSONObject(j);
                                                    if (!Check.isNull(materialJson)) {
                                                        Long photo_id = materialJson.getLong("photo_id");
                                                        photoIds.add(String.valueOf(photo_id));
                                                    }
                                                }
                                                creative.setPhotoIds(photoIds.toJSONString());
                                            }
                                        }
                                    }
                                    creativeService.saveOrUpdate(creative);
                                }

                            }

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

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


    /**
     * 获取token
     *
     * @param authCode
     * @return
     */
    @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);
            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 Map<String, Object> getDeepConversionInfos(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");
        Map<String, Object> resultMap = new HashMap<>();
        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");
                Integer isActivate;
                Integer isFormSubmit;
                if (code == 0) {
                    Map<String, Object> deleteMap = new HashMap<>();
                    deleteMap.put("account_id", advertiserId);
                    //删除历史数据
                    conversionInfosMapper.deleteByMap(deleteMap);
                    conversionTypesMapper.deleteByMap(deleteMap);
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNullMap(dataJson)) {
                        KuaiShouConversionInfos conversionInfos = new KuaiShouConversionInfos();
                        conversionInfos.setAccountId(advertiserId);
                        isActivate = dataJson.getInteger("is_activate");
                        isFormSubmit = dataJson.getInteger("is_form_submit");
                        conversionInfos.setIsActivate(isActivate);
                        conversionInfos.setIsFormSubmit(isFormSubmit);
                        conversionInfosMapper.insert(conversionInfos);
                        JSONArray conversionTypeArr = dataJson.getJSONArray("deep_conversion_types");
                        if (!Check.isNull(conversionTypeArr)) {
                            for (int i = 0; i < conversionTypeArr.size(); i++) {
                                JSONObject conversionType = JSONObject.parseObject(conversionTypeArr.get(i).toString());
                                if (!Check.isNull(conversionType)) {
                                    KuaiShouConversionTypes conversionTypes = new KuaiShouConversionTypes();
                                    conversionTypes.setAccountId(advertiserId);
                                    conversionTypes.setDeepConversionTypes(conversionType.getInteger("deep_conversion_type"));
                                    conversionTypes.setDescStr(conversionType.getString("desc"));
                                    conversionTypesMapper.insert(conversionTypes);
                                }
                            }
                        }
                        resultMap.put("isActivate", isActivate);
                        resultMap.put("isFormSubmit", isFormSubmit);
                        resultMap.put("deepConversionTypes", conversionTypeArr);
                        resultMap.put("code", 0);
                        resultMap.put("success", true);
                        resultMap.put("message", "查询成功");
                    }
                } else {
                    log.error("获取可选的深度转化类型返回异常,advertiserId:{},异常信息:{}", advertiserId, resultJson);
                    resultMap.put("code", -1);
                    resultMap.put("success", false);
                    resultMap.put("message", "获取可选的深度转化类型返回异常");
                }
            } else {
                log.error("快手，获取可选的深度转化类型返回为空，advertiserId：{}", advertiserId);
                resultMap.put("code", -1);
                resultMap.put("success", false);
                resultMap.put("message", "获取可选的深度转化类型返回为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", -1);
            resultMap.put("success", false);
            resultMap.put("message", "接口异常");
        }
        return resultMap;

    }


    @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"));
                        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 accessToken
     * @param advertiserId
     * @param requestJson
     */
    @Override
    public Map<String, Object> creativeCreate(String accessToken, Long advertiserId, JSONObject requestJson, Integer count) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AD_CREATIVE_CREATE;
            requestJson.put("advertiser_id", advertiserId);
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", " application/json");
            header.put("Access-Token", accessToken);

            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), header);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("快手创建创意返回：accountId:{}，返回结果{}", advertiserId, resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        Long creativeId = dataJson.getLong("creative_id");
                        Thread thread = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(100);
                                    getCreativeByCreativeId(accessToken, advertiserId, creativeId);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                            }

                        };
                        thread.start();
                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                        returnMap.put("success", true);
                    }
                } else {
                    if (code == 500000 && count <= 4) {
                        creativeCreate(accessToken, advertiserId, requestJson, count + 1);
                    }
                    log.error("创建广告创意失败,advertiser_id:{},返回信息：{}，入参：{}", advertiserId, resultJson, requestJson, count + 1);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "创意创建失败");
                    returnMap.put("success", false);
                }
            } else {
                if (count <= 4) {
                    creativeCreate(accessToken, advertiserId, requestJson, count + 1);
                }

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

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

    }


    @Override
    public Map<String, Object> videoUpload(Long advertiserId, String accessToken, String videoUrl) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            QueryWrapper<KuaiShouVideoUpload> wrapper = new QueryWrapper<>();
            wrapper.eq("account_id", advertiserId).eq("sava_path", videoUrl).orderByDesc("create_time");
            wrapper.last("limit 1");
            KuaiShouVideoUpload videoUpload = videoUploadMapper.selectOne(wrapper);
            if (!Check.isNull(videoUpload)) {
                returnMap.put("code", 0);
                returnMap.put("message", "视频已上传文件");
                returnMap.put("success", true);
                returnMap.put("photoId", videoUpload.getPhotoId());
                return returnMap;
            }
            String localUrl = LoadFileUtil.downLoadFromUrl(videoUrl, PropertiesUtils.getValue("kuaishou_config", "video_sava_path"));
            if (Check.isNull(localUrl)) {
                log.error("下载文件到本地文件夹失败，filePath:{},accountId:{}", videoUrl, advertiserId);
                throw new Exception("下载文件到本地失败");
            }

            QueryWrapper<MaterialInfo> materialInfoQueryWrapper = new QueryWrapper<>();
            materialInfoQueryWrapper.eq("url", videoUrl);
            materialInfoQueryWrapper.eq("status", 1);
            materialInfoQueryWrapper.orderByDesc("create_time");
            materialInfoQueryWrapper.last("limit 1");
            MaterialInfo materialInfo = materialInfoMapper.selectOne(materialInfoQueryWrapper);
            String signature;
            if (Check.isNull(materialInfo) || Check.isNull(materialInfo.getCode())) {
                signature = LoadFileUtil.getMD5(localUrl);
            } else {
                signature = materialInfo.getCode();
            }
            Long startTime = System.currentTimeMillis();
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.VIDEO_UPLOAD;
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", advertiserId);
            requestJson.put("signature", signature);
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Access-Token", accessToken);
            headerMap.put("Content-Type", "multipart/form-data");
            String result = exceptInfoForRestTemplate(url, requestJson, headerMap, localUrl);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(result)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        KuaiShouVideoUpload kuaiShouVideoUpload = new KuaiShouVideoUpload();
                        String photoId = dataJson.getString("photo_id");
                        kuaiShouVideoUpload.setPhotoId(photoId);
                        kuaiShouVideoUpload.setAccountId(advertiserId);
                        kuaiShouVideoUpload.setSavaPath(videoUrl);
                        kuaiShouVideoUpload.setSignature(dataJson.getString("signature"));
                        kuaiShouVideoUpload.setSize(null);
                        kuaiShouVideoUpload.setType(null);
                        kuaiShouVideoUpload.setUploadTime(DateUtils.timeStamp2Date(System.currentTimeMillis()));
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("photo_id", photoId);
                        deleteMap.put("account_id", advertiserId);
                        videoUploadMapper.deleteByMap(deleteMap);
                        int i = videoUploadMapper.insert(kuaiShouVideoUpload);
                        if (i > 0) {
                            log.info("上传快手视频完成");
                        }

                        KuaiShouVideo video = new KuaiShouVideo();
                        video.setStatus(1);
                        QueryWrapper<KuaiShouVideo> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("account_id", advertiserId);
                        queryWrapper.eq("local_url", videoUrl);
                        int y = kuaiShouVideoMapper.update(video, queryWrapper);
                        if (y > 0) {
                            log.info("更新快手视频状态成功.accountId:{}，上传耗时:{} ms", advertiserId, System.currentTimeMillis() - startTime);
                        }

                        returnMap.put("code", 0);
                        returnMap.put("message", "视频已上传文件");
                        returnMap.put("success", true);
                        returnMap.put("photoId", photoId);
                        return returnMap;
                    }
                } else {
                    log.error("快手上传视频返回信息异常 ，advertiserId：{}，异常信息：{}", advertiserId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("success", false);
                    return returnMap;
                }
            } else {
                log.error("快手上传视频返回信息为空，advertiserId：{}", advertiserId);
                returnMap.put("code", -1);
                returnMap.put("message", "视频上传失败");
                returnMap.put("success", false);
                return returnMap;
            }
        } catch (Exception e) {
            log.error("上传视频失败,advertiser_id:{}", advertiserId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("message", "上传视频异常");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            return returnMap;
        }
        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 accessToken
     */
    @Override
    public void areaList(String accessToken) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.REGION_LIST;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            String result = HttpUtils.httpGet(url, null, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    regionListParentMapper.deleteAll();
                    regionListChildrenMapper.deleteAll();
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        for (Map.Entry<String, Object> entry : dataJson.entrySet()) {
                            String key = entry.getKey();
                            JSONObject keyJson = dataJson.getJSONObject(key);
                            if (!Check.isNull(keyJson)) {
                                KuaiShouRegionListParent regionListParent = new KuaiShouRegionListParent();
                                Long id = keyJson.getLong("id");
                                regionListParent.setRegionId(id);
                                regionListParent.setLevel(keyJson.getInteger("level"));
                                regionListParent.setName(keyJson.getString("name"));
                                regionListParent.setParent(keyJson.getLong("parent"));
                                regionListParentMapper.insert(regionListParent);
                                JSONArray childrenArr = keyJson.getJSONArray("children");
                                if (!Check.isNull(childrenArr)) {
                                    for (int i = 0; i < childrenArr.size(); i++) {
                                        KuaiShouRegionListChildren regionListChildren = new KuaiShouRegionListChildren();
                                        regionListChildren.setParentId(id);
                                        regionListChildren.setRegionId(childrenArr.getLong(i));
                                        regionListChildrenMapper.insert(regionListChildren);

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

    /**
     * 图片上传
     *
     * @param advertiserId
     * @param accessToken
     * @param filePath
     * @param type
     */
    @Override
    public Map<String, Object> imageUpload(Long advertiserId, String accessToken, String filePath, Integer type) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            QueryWrapper<KuaiShouImageUploand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", advertiserId).eq("sava_path", filePath).orderByDesc("create_time");
            queryWrapper.last("limit 1");
            KuaiShouImageUploand kuaiShouImageUploand = imageUploandMapper.selectOne(queryWrapper);
            if (!Check.isNull(kuaiShouImageUploand)) {
                returnMap.put("code", 0);
                returnMap.put("message", "图片已上传文件已上传");
                returnMap.put("success", true);
                returnMap.put("imageToken", kuaiShouImageUploand.getImageToken());
                return returnMap;
            }
            String localUrl = LoadFileUtil.downLoadFromUrl(filePath, PropertiesUtils.getValue("kuaishou_config", "image_sava_path"));
            if (Check.isNull(localUrl)) {
                log.error("下载文件到本地文件夹失败，filePath:{},accountId:{}", filePath, advertiserId);
                throw new Exception("下载文件到本地失败");
            }
            String signature = LoadFileUtil.getMD5(localUrl);
            Long startTime = System.currentTimeMillis();
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.IMAGE_UPLOAD;
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", advertiserId);
            requestJson.put("signature", signature);
            requestJson.put("type", type);
            requestJson.put("upload_type", 1);
            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Content-Type", "multipart/form-data");
            headerMap.put("Access-Token", accessToken);
            String result = exceptInfoForRestTemplate(url, requestJson, headerMap, localUrl);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(result)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        KuaiShouImageUploand imageUploand = new KuaiShouImageUploand();
                        imageUploand.setAccountId(advertiserId);
                        imageUploand.setSavaPath(filePath);
                        imageUploand.setUploadTime(new Date().toString());
                        imageUploand.setUrl(dataJson.getString("url"));
                        imageUploand.setImageToken(dataJson.getString("image_token"));
                        imageUploand.setHeight(dataJson.getLong("height"));
                        imageUploand.setSize(dataJson.getLong("size"));
                        imageUploand.setFormat(dataJson.getString("format"));
                        imageUploand.setWidth(dataJson.getLong("width"));
                        int i = imageUploandMapper.insert(imageUploand);
                        if (i > 0) {
                            log.info("快手-图片上传成功，共耗时:{} ms", System.currentTimeMillis() - startTime);
                        }
                        returnMap.put("code", 0);
                        returnMap.put("desc", "上传图片完成");
                        returnMap.put("imageToken", dataJson.getString("image_token"));
                        returnMap.put("success", true);
                        return returnMap;
                    }

                } else {
                    log.error("快手上传图片返回信息异常 ，advertiserId：{}，异常信息：{}", advertiserId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("desc", "error");
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("success", false);
                }
            } else {
                log.error("快手上传图片返回信息为空，advertiserId：{}", advertiserId);
                returnMap.put("code", -1);
                returnMap.put("desc", "error");
                returnMap.put("message", "上传图片失败失败");
                returnMap.put("success", false);
            }
            LoadFileUtil.delFile(localUrl);

        } catch (Exception e) {
            log.error("上传图片失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "上传图片异常");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 创建应用
     *
     * @param advertiserId
     * @param accessToken
     * @param requestJson
     */
    @Override
    public Map<String, Object> appCreate(Long advertiserId, String accessToken, JSONObject requestJson) {
        log.info("快手创建file应用");
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String filePath = requestJson.getString("file");

            QueryWrapper<KuaiShouAppCreate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", advertiserId).eq("sava_path", filePath).orderByDesc("create_time");
            queryWrapper.last("limit 1");
            KuaiShouAppCreate kuaiShouAppCreate = appCreateMapper.selectOne(queryWrapper);
            if (!Check.isNull(kuaiShouAppCreate)) {
                log.info("file应用已经存在");
                returnMap.put("code", 0);
                returnMap.put("message", "文件已上传");
                returnMap.put("success", true);
                returnMap.put("appId", kuaiShouAppCreate.getAppId());
                return returnMap;
            }
            String localUrl = LoadFileUtil.downLoadFromUrl(filePath, PropertiesUtils.getValue("kuaishou_config", "apk_sava_path"));
            if (Check.isNull(localUrl)) {
                log.error("下载文件到本地文件夹失败，filePath:{},accountId:{}", filePath, advertiserId);
                throw new Exception("下载文件到本地失败");
            }
            requestJson.put("advertiser_id", advertiserId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_CREATE;
            Map<String, String> header = new HashMap<String, String>();
            header.put("Content-Type", "multipart/form-data");
            header.put("Access-Token", accessToken);
            Long startTime = System.currentTimeMillis();
            String result = exceptInfoForRestTemplate(url, requestJson, header, localUrl);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(result)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        requestJson.put("url", dataJson.getString("url"));
                        requestJson.put("app_id", dataJson.getLong("app_id"));
                        this.insertAppList(advertiserId, requestJson);
                        log.info("应用创建成功，耗时:{} s", (System.currentTimeMillis() - startTime) / 1000);
                        returnMap.put("appId", dataJson.getLong("app_id"));
                        returnMap.put("success", true);
                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                    }

                } else {
                    log.error("快手创建应用返回信息异常 ，advertiserId：{}，异常信息：{}", advertiserId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("desc", "Interface exception");
                    returnMap.put("success", false);
                }
            } else {
                log.error("快手创建应用返回信息为空，advertiserId：{}", advertiserId);
                returnMap.put("code", -1);
                returnMap.put("message", "上传apk文件失败");
                returnMap.put("desc", "Interface exception");
                returnMap.put("success", false);
            }
            LoadFileUtil.delFile(localUrl);

        } catch (Exception e) {
            log.error("创建应用失败,advertiser_id:{}", advertiserId);
            returnMap.put("code", -1);
            returnMap.put("message", "上传apk文件错误");
            returnMap.put("desc", "Interface exception");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @Override
    public Map<String, Object> urlAppCreate(Long accountId, String accessToken, JSONObject apkJson) {
        log.info("快手创建url应用");
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String appUrl = apkJson.getString("url");
            String appVersion = apkJson.getString("app_version");
            String appName = apkJson.getString("app_name");
            QueryWrapper<KuaiShouAppCreate> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", accountId).eq("url", appUrl).eq("app_version", appVersion).eq("app_name", appName).orderByDesc("create_time");
            queryWrapper.last("limit 1");
            KuaiShouAppCreate kuaiShouAppCreate = appCreateMapper.selectOne(queryWrapper);
            if (!Check.isNull(kuaiShouAppCreate)) {
                log.info("url应用已经存在");
                returnMap.put("code", 0);
                returnMap.put("message", "文件已上传");
                returnMap.put("success", true);
                returnMap.put("appId", kuaiShouAppCreate.getAppId());
                return returnMap;
            }
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_CREATE;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "multipart/form-data");
            apkJson.put("advertiser_id", accountId + "");
            String result = exceptInfoForRestTemplate(url, apkJson, headers, null);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(result)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject dataJson = resultJson.getJSONObject("data");
                    if (!Check.isNull(dataJson)) {
                        apkJson.put("url", dataJson.getString("url"));
                        apkJson.put("app_id", dataJson.getLong("app_id"));
                        this.insertAppList(accountId, apkJson);

                        returnMap.put("code", 0);
                        returnMap.put("message", "success");
                        returnMap.put("appId", dataJson.getLong("app_id"));
                        returnMap.put("success", true);
                    }
                } else {
                    log.error("快手创建应用返回信息异常 ，advertiserId：{}，异常信息：{}", accountId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("message", resultJson.getString("message"));
                    returnMap.put("success", false);
                }
            } else {
                log.error("快手创建应用返回信息为空，advertiserId：{}", accountId);
                returnMap.put("code", -1);
                returnMap.put("message", "apk文件url上传异常");
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            log.error("创建应用失败,advertiser_id:{}", accountId);
            returnMap.put("code", -1);
            returnMap.put("message", "应用url创建应用异常");
            e.printStackTrace();
        }
        return returnMap;
    }


    /**
     * 添加 应用信息
     */
    private void insertAppList(Long accountId, JSONObject dataJson) {

        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("account_id", accountId);
        deleteMap.put("app_version", dataJson.getString("app_version"));
        appListMapper.deleteByMap(deleteMap);
        KuaiShouAppList appList = new KuaiShouAppList();
        appList.setAccountId(accountId);
        appList.setUrl(dataJson.getString("url"));
        appList.setPlatform(dataJson.getInteger("platform"));
        appList.setAppVersion(dataJson.getString("app_version"));
        appList.setAppName(dataJson.getString("app_name"));
        appList.setImageToken(dataJson.getString("image_token"));
        appList.setPackageName(dataJson.getString("package_name"));
        appList.setAppId(dataJson.getLong("app_id"));
        appList.setAppIconUrl(dataJson.getString("app_icon_url"));
        appList.setReturnTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm"));
        int i = appListMapper.insert(appList);
        if (i > 0) {
            log.info("同步应用成功");
        }

    }


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

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

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


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


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

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

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

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


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


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

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

               /* if (Check.isNull(detailJson.getString("signature"))) {
                    continue;
                }*/

                var kuaiShouImageGet = JSONObject.toJavaObject(detailJson, KuaiShouImageGet.class);

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

                Integer type = MaterialEnum.getTypeBySize(kuaiShouImageGet.getWidth(), kuaiShouImageGet.getHeight());
                if (!Check.isNull(type)) {
                    kuaiShouImageGet.setMaterialType(type);
                }
                kuaiShouImageGet.setStatDate(DateUtils.parseDate(statDate, "yyyy-MM-dd"));

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

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


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


    @Override
    public void getPopulationList(Long accountId, String accessToken) {
        try {
            log.info("获取人群包列表，accountId:{}", accountId);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.POPULATION_LIST;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("status", 4);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONArray dataArr = resultJson.getJSONArray("data");
                    if (!Check.isNull(dataArr)) {
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("account_id", accountId);
                        populationService.removeByMap(deleteMap);
                        for (int i = 0; i < dataArr.size(); i++) {
                            JSONObject dataJson = dataArr.getJSONObject(i);
                            if (!Check.isNull(dataJson)) {
                                KuaishouPopulation population = new KuaishouPopulation();
                                population.setOrientationId(dataJson.getLong("orientation_id"));
                                population.setOrientationName(dataJson.getString("orientation_name"));
                                population.setType(dataJson.getInteger("type"));
                                population.setPopulationType(dataJson.getInteger("population_type"));
                                population.setRecordSize(dataJson.getLong("record_size"));
                                population.setMatchSize(dataJson.getLong("match_size"));
                                population.setCoverNum(dataJson.getLong("cover_num"));
                                population.setStatus(dataJson.getInteger("status"));
                                population.setPutTime(dataJson.getDate("create_time"));
                                population.setThirdPlatformCode(dataJson.getLong("third_platform_code"));
                                population.setAccountId(accountId);
                                populationService.save(population);

                            }
                        }

                    }

                } else {
                    log.error("获取人群包管理返回数据为空，accountId:{}", accountId);

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


    }


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


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


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

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

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

        return null;
    }

    /**
     * 获取素造数据
     *
     * @param token
     * @param accountId
     * @param page
     */
    @Autowired
    private IKuaiShouVideoGetService videoGetService;

    @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);
        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)) {
            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);
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            videoGetService.getKeyFrame(token, accountId, md5, String.valueOf(photo_id));
                        }
                    };
                    thread.start();


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

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

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

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

            }


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

        }


    }

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

        return convertVoList;
    }

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

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

        return null;
    }


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

            e.printStackTrace();
        }
        return returnArr;
    }

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

    private void getAppList2ByPage(Long advertiserId, String accessToken, Integer page, Integer pageSize) {
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.APP_LIST_v2;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", " application/json");
            JSONObject json = new JSONObject();
            json.put("advertiser_id", advertiserId);
            json.put("page", page);
            json.put("page_size", pageSize);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, json.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    if (page == 1) { //分页保存数据，如果页数为1，删除之前的数据重新入库
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("account_id", advertiserId);
                        appListMapper.deleteByMap(deleteMap);
                    }
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        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)) {
                                KuaiShouAppList appList = new KuaiShouAppList();
                                appList.setAccountId(advertiserId);
                                appList.setPlatform(dataJson.getInteger("platform"));
                                appList.setUrl(dataJson.getString("url"));
                                appList.setAppId(dataJson.getLong("app_id"));
                                appList.setAppVersion(dataJson.getString("app_version"));
                                appList.setAppName(dataJson.getString("app_name"));
                                appList.setAppIconUrl(dataJson.getString("app_icon_url"));
                                appList.setImageToken(dataJson.getString("image_token"));
                                appList.setPackageName(dataJson.getString("package_name"));
                                appList.setReturnTime(DateUtils.timeStamp2Date(dataJson.getTimestamp("update_time")));
                                appListMapper.insert(appList);
                            }
                        }
                        Integer totalPage = (totalCount - 1) / pageSize + 1;
                        if (page < totalPage) {
                            getAppList2ByPage(advertiserId, accessToken, page + 1, pageSize);
                        }
                    }
                } else {
                    log.error("获取应用列表失败，返回信息：{}", resultJson);
                }
            } else {
                log.error("获取地域列表返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
