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

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouAppPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouPopulationGroupService;
import cn.com.ctop.kuaishou.modules.batch.entity.*;
import cn.com.ctop.kuaishou.modules.batch.mapper.*;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yumeng
 * 2019年11月12日10:04:00
 */
@Slf4j
@Service
public class KuaiShouUpdateServiceImpl implements IKuaiShouUpdateService {
    @Resource
    private KuaiShouCampaignMapper campaignMapper;
    @Resource
    private KuaiShouCampaignDayBudgetMapper campaignDayBudgetMapper;
    @Resource
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private IKuaiShouGroupService groupService;
    @Resource
    private KuaiShouGroupDayBudgetMapper groupDayBudgetMapper;
    @Resource
    private IKuaishouInterfaceService interfaceService;
    @Resource
    private KuaiShouGroupBidMapper groupBidMapper;
    @Resource
    private KuaiShouCampaignStatusMapper campaignStatusMapper;
    @Resource
    private KuaiShouCampaignMapper kuaiShouCampaignMapper;
    @Resource
    private KuaiShouCreativeMapper creativeMapper;
    @Autowired
    private IKuaishouDirectionalPackageService directionalPackageService;
    @Autowired
    private IKuaishouPopulationGroupService populationGroupService;
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;
    @Autowired
    private IKuaishouAppPackageService appPackageService;

    @Override
    public Map<String, Object> updateCampaign(String token, Long advertiserId, Long campaignId, Long dayBudget, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CAMPAIGN_BUDGET;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            JSONObject params = new JSONObject();
            params.put("advertiser_id", advertiserId);
            params.put("campaign_id", campaignId);
            params.put("day_budget", dayBudget);
            String result = HttpUtils.httpPostRequest(url, params, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    QueryWrapper<KuaiShouCampaign> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("account_id", advertiserId);
                    queryWrapper.eq("campaign_id", campaignId);
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    // 查询本地记录信息
                    KuaiShouCampaign campaign = campaignMapper.selectOne(queryWrapper);
                    KuaiShouCampaignDayBudget campaignDayBudget = new KuaiShouCampaignDayBudget();
                    campaignDayBudget.setAccountId(advertiserId);
                    campaignDayBudget.setCampaignId(campaignId);
                    campaignDayBudget.setUserId(loginId);
                    campaignDayBudget.setDayBudget(campaign.getDayBudget());
                    campaignDayBudget.setUpdateDayBudget(dayBudget);
                    int i = campaignDayBudgetMapper.insert(campaignDayBudget);
                    if (i > 0) {
                        log.info("修改广告计划预算记录表添加成功，campaignId：{}", campaignId);
                    }
                    interfaceService.getCampaign(token, advertiserId, campaignId);
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");

                } else {
                    log.error("修改广告计划预算失败，advertiserId：{}，campaignId：{}，返回信息：{}", advertiserId, campaignId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告计划预算返回结果为空，advertiserId：{}，campaignId：{}", advertiserId, campaignId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告计划预算返回结果为空");
            }

        } catch (Exception e) {
            log.error("修改广告计划预算异常，advertiserId：{}，campaignId：{}", advertiserId, campaignId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告计划预算异常");
        }


        return returnMap;
    }


    /**
     * 修改广告组预算
     *
     * @param token
     * @param advertiserId
     * @param unitId
     * @param dayBudget
     * @return
     */
    @Override
    public Map<String, Object> updateUnitDayBudget(String token, Long advertiserId, Long unitId, Long dayBudget, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT_BUDGET;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            JSONObject params = new JSONObject();
            params.put("day_budget", dayBudget);
            params.put("advertiser_id", advertiserId);
            params.put("unit_id", unitId);
            String result = HttpUtils.httpPostRequest(url, params, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("account_id", advertiserId);
                    queryWrapper.eq("unit_id", unitId);
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    KuaiShouGroup group = groupMapper.selectOne(queryWrapper);

                    KuaiShouGroupDayBudget groupDayBudget = new KuaiShouGroupDayBudget();
                    groupDayBudget.setAccountId(advertiserId);
                    groupDayBudget.setUnitId(unitId);
                    groupDayBudget.setDayBudget(group.getDayBudget());
                    groupDayBudget.setUpdateDayBudget(dayBudget);
                    groupDayBudget.setUserId(loginId);
                    int i = groupDayBudgetMapper.insert(groupDayBudget);
                    if (i > 0) {
                        log.info("修改广告组预算本地记录添加成功，unitId：{}", unitId);
                    }
                    // 重新请求数据
                    groupService.getGroupByUnitId(token, advertiserId, unitId);
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                } else {
                    log.error("修改广告组预算失败，advertiserId：{}，unitId：{}，返回信息：{}", advertiserId, unitId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告组预算返回结果为空，advertiserId：{}，unitId：{}", advertiserId, unitId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }

        } catch (Exception e) {
            log.error("修改广告组算异常，advertiserId：{}，unitId：{}", advertiserId, unitId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告组预算异常");
        }

        return returnMap;
    }

    /**
     * 修改广告组出价
     *
     * @param token
     * @param advertiserId
     * @param unitId
     * @param bid
     * @return
     */
    @Override
    public Map<String, Object> updateUnitBid(String token, Long advertiserId, Long unitId, Long bid, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT_BID;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);

            JSONObject params = new JSONObject();
            params.put("advertiser_id", advertiserId);
            params.put("bid", bid);
            params.put("unit_id", unitId);
            String result = HttpUtils.httpPostRequest(url, params, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("unit_id", unitId);
                    queryWrapper.eq("account_id", advertiserId);
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    KuaiShouGroup group = groupMapper.selectOne(queryWrapper);

                    KuaiShouGroupBid groupBid = new KuaiShouGroupBid();
                    groupBid.setAccountId(advertiserId);
                    groupBid.setUnitId(unitId);
                    groupBid.setBid(group.getBid());
                    groupBid.setUpdateBid(bid);
                    groupBid.setUserId(loginId);
                    int i = groupBidMapper.insert(groupBid);
                    if (i > 0) {
                        log.info("修改广告组出价本地记录添加成功，unitId：{}", unitId);
                    }
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                } else {
                    log.error("修改广告组出价失败，advertiserId：{}，unitId：{}，返回信息：{}", advertiserId, unitId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告组出价返回结果为空，advertiserId：{}，unitId：{}", advertiserId, unitId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }

        } catch (Exception e) {
            log.error("修改广告组出价异常，advertiserId：{}，unitId：{}", advertiserId, unitId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告组出价异常");
        }

        return returnMap;
    }


    /**
     * 修改广告计划状态
     *
     * @param token
     * @param advertiserId
     * @param campaignId
     * @param putStatus
     * @return
     */
    @Override
    public Map<String, Object> updateCampaignStatus(String token, Long advertiserId, Long campaignId, int putStatus, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CAMPAIGN_STATUS;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", token);
            headers.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("advertiser_id", advertiserId);
            params.put("put_status", putStatus);
            params.put("campaign_id", campaignId);

            String result = HttpUtils.httpPostRequest(url, params, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    QueryWrapper<KuaiShouCampaign> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("campaign_id", campaignId);
                    queryWrapper.eq("account_id", advertiserId);
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    // 查询本地记录信息
                    KuaiShouCampaign campaign = campaignMapper.selectOne(queryWrapper);

                    KuaiShouCampaignStatus campaignStatus = new KuaiShouCampaignStatus();
                    campaignStatus.setAccountId(advertiserId);
                    campaignStatus.setCampaignId(campaignId);
                    campaignStatus.setPutStatus(campaign.getStatus());
                    campaignStatus.setUpdatePutStatus(putStatus);
                    campaignStatus.setUserId(loginId);
                    int i = campaignStatusMapper.insert(campaignStatus);
                    if (i > 0) {
                        log.info("修改广告计划状态本地记录添加成功，campaignId：{}", campaignId);
                    }
                    if (putStatus == 3) {
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("account_id", advertiserId);
                        deleteMap.put("campaign_id", campaignId);
                        kuaiShouCampaignMapper.deleteByMap(deleteMap);
                    } else {
                        interfaceService.getCampaign(token, advertiserId, campaignId);
                    }
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                } else {
                    log.error("修改广告计划状态失败，advertiserId：{}，campaignId：{}，返回信息：{}", advertiserId, campaignId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告计划状态返回结果为空，advertiserId：{}，campaignId：{}", advertiserId, campaignId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }
        } catch (Exception e) {
            log.error("修改广告计划状态异常，advertiserId：{}，campaignId：{}", advertiserId, campaignId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告计划状态算异常");
        }
        return returnMap;
    }


    /**
     * TODO
     * 修改广告组状态
     *
     * @param token
     * @param advertiserId
     * @param unitId
     * @param putStatus
     * @return
     */
    @Override
    public Map<String, Object> updateUnitStatus(String token, Long advertiserId, Long unitId, int putStatus, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT_STATUS;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("advertiser_id", advertiserId);
            params.put("unit_id", unitId);
            params.put("put_status", putStatus);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                    if (putStatus == 3) {
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("account_id", advertiserId);
                        deleteMap.put("unit_id", unitId);
                        groupMapper.deleteByMap(deleteMap);
                    } else {
                        groupService.getGroupByUnitId(token, advertiserId, unitId);
                    }
                    log.info("删除成功，accountId：{}。unitId：{}", advertiserId, unitId);
                } else {
                    log.error("修改广告组状态失败，advertiserId：{}，unitId：{}，返回信息：{}", advertiserId, unitId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告组状态返回结果为空，advertiserId：{}，unitId：{}", advertiserId, unitId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }
        } catch (Exception e) {
            log.error("修改广告组状态异常，advertiserId：{}，unitId：{}", advertiserId, unitId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告组状态异常");
        }

        return returnMap;
    }

    /**
     * 修改 广告创意状态
     *
     * @param token
     * @param advertiserId
     * @param creativeId
     * @param putStatus
     * @return
     */
    @Override
    public Map<String, Object> updateCreativeStatus(String token, Long advertiserId, Long creativeId, int putStatus, String loginId) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CREATIVE_STATUS;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("put_status", putStatus);
            params.put("advertiser_id", advertiserId);
            params.put("creative_id", creativeId);
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    if (putStatus == 3) {
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("account_id", advertiserId);
                        deleteMap.put("creative_id", creativeId);
                        creativeMapper.deleteByMap(deleteMap);
                    } else {
                        interfaceService.getCreativeByCreativeId(token, advertiserId, creativeId);
                    }

                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                } else {
                    log.error("修改广告创意状态失败，advertiserId：{}，creativeId：{}，返回信息：{}", advertiserId, creativeId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告创意状态返回结果为空，advertiserId：{}，creativeId：{}", advertiserId, creativeId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }

        } catch (Exception e) {
            log.error("修改广告创意状态异常，advertiserId：{}，creativeId：{}", advertiserId, creativeId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告创意状态异常");
        }

        return returnMap;
    }


    /**
     * 修改创意
     *
     * @param token
     * @param advertiserId
     * @param requestJson
     * @return
     */
    @Override
    public Map<String, Object> updateCreative(String token, Long advertiserId, JSONObject requestJson) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CREATIVE;
            Map<String, String> header = new HashMap<>();
            header.put("Access-Token", token);
            header.put("Content-Type", "application/json");
            JSONObject params = new JSONObject();
            params.put("advertiser_id", advertiserId);
            String creativeId = requestJson.getString("creativeId");
            String creativeName = requestJson.getString("creativeName");
            String description = requestJson.getString("description");
            String action_bar_text = requestJson.getString("actionBarText");
            if (!Check.isNull(creativeId)) {
                params.put("creative_id", creativeId);
            }
            if (!Check.isNull(creativeName)) {
                params.put("creative_name", creativeName);
            }
            if (!Check.isNull(description)) {
                params.put("description", description);
            }
            if (!Check.isNull(action_bar_text)) {
                params.put("action_bar_text", action_bar_text);
            }
            if (!Check.isNull(requestJson.getString("imageToken"))) {
                params.put("image_token", requestJson.getString("imageToken"));
            }
            String result = HttpUtils.httpPostRequest(url, params, header);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                    returnMap.put("message", "修改成功");
                    Thread.sleep(50);
                    interfaceService.getCreativeByCreativeId(token, advertiserId, Long.valueOf(creativeId));

                } else {
                    log.error("修改广告创意状态失败，advertiserId：{}，creativeId：{}，返回信息：{}", advertiserId, creativeId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                    if ("该账户下创意不存在".equals(resultJson.getString("message"))) {
                        Map<String, Object> deleteMap = new HashMap<>();
                        deleteMap.put("creative_id", creativeId);
                        creativeMapper.deleteByMap(deleteMap);
                    }


                }
            } else {
                log.error("修改广告创意返回结果为空，advertiserId：{}，creativeId：{}", advertiserId, creativeId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }

        } catch (Exception e) {
            log.error("修改广告创意异常，advertiserId：{}", advertiserId);
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("success", false);
            returnMap.put("message", "修改广告创意异常");
        }

        return returnMap;
    }


    @Override
    public JSONObject updateCampaign(String accessToken, JSONObject requestJson) {
        JSONObject returnJson = new JSONObject();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CAMPAIGN;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            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 data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        try {
                            Thread.sleep(500);
                            interfaceService.getCampaign(accessToken, requestJson.getLong("advertiser_id"), data.getLong("campaign_id"));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        returnJson.put("code", 0);
                    } else {
                        returnJson.put("code", -1);
                        returnJson.put("message", "返回信息为空");
                    }

                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    /**
     * 修改广告组
     *
     * @param accessToken
     * @param unitJson
     * @return
     */

    @Override
    public JSONObject updateUnit(String accessToken, JSONObject unitJson) {
        JSONObject returnJson = new JSONObject();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, unitJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("修改广告组返回信息：{}", resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {
                        //添加广告组和定向模板、人群包绑定关系
                        Thread thread2 = new Thread() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject request = new JSONObject();
                                    request.put("accountId", unitJson.getLong("advertiser_id"));
                                    request.put("unitId", data.getLong("unit_id"));
                                    JSONObject target = unitJson.getJSONObject("target");
                                    if (!Check.isNull(target)) {
                                        request.put("excludePopulation", target.getJSONArray("exclude_population"));
                                        request.put("population", target.getJSONArray("population"));
                                        request.put("paidAudience", target.getJSONArray("paid_audience"));
                                        populationGroupService.createPopulationAndGroupRel(request);
                                    }
                                    if (!Check.isNull(unitJson.getLong("template_id"))) {
                                        request.put("templateId", unitJson.getLong("template_id"));
                                        directionalPackageService.createUnitAndTemplate(request);
                                    }
                                    if (!Check.isNull(unitJson.getLong("app_id"))) {
                                        request.put("appId", unitJson.getLong("app_id"));
                                        appPackageService.createAppAndGroupRel(request);
                                    }
                                } catch (Exception e) {
                                    log.error("添加广告组和定向模板、人群包绑定关系异常，", e);
                                }
                            }
                        };
                        thread2.start();
                        try {
                            Thread.sleep(500);
                            groupService.getGroupByUnitId(accessToken, unitJson.getLong("advertiser_id"), data.getLong("unit_id"));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        returnJson.put("code", 0);
                    } else {
                        returnJson.put("code", -1);
                        returnJson.put("message", "返回信息为空");
                    }

                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }


        return returnJson;
    }


    /**
     * 修改 广告创意
     *
     * @param accessToken
     * @param creativeJson
     * @return
     */
    @Override
    public JSONObject updateCreative(String accessToken, JSONObject creativeJson) {
        JSONObject returnJson = new JSONObject();
        try {
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_CREATIVE;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, creativeJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONObject data = resultJson.getJSONObject("data");
                    if (!Check.isNull(data)) {

                        try {
                            Thread.sleep(200);
                            interfaceService.getCreativeByCreativeId(accessToken, creativeJson.getLong("advertiser_id"), data.getLong("creative_id"));
                            createLandPageAndUnit(creativeJson, resultJson.getJSONObject("data"));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }


                        returnJson.put("code", 0);
                    } else {
                        returnJson.put("code", -1);
                        returnJson.put("message", "返回信息为空");
                    }

                } else {
                    returnJson.put("code", -1);
                    returnJson.put("message", resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnJson.put("code", -1);
            returnJson.put("message", e.getMessage());
        }


        return returnJson;
    }

    //绑定落地页与广告组、创意的关系
    private void createLandPageAndUnit(JSONObject programJson, JSONObject data) {
        if (!Check.isNull(data) && !Check.isNull(programJson.getLong("site_id"))) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    landpagePackageService.createLandPageAndUnit(programJson.getLong("site_id"), data.getLong("creative_id"), programJson.getLong("unit_id"), programJson.getLong("advertiser_id"));
                }
            };
            thread.start();
        }
    }

    @Override
    public Map<String, Object> updateUnitDeepConversionBid(String accessToken, Long accountId, Long unitId, Long deepConversionBid, String userId) {

        Map<String, Object> returnMap = new HashMap<>();
        try {

            JSONObject updateJson = new JSONObject();
            updateJson.put("advertiser_id", accountId);
            updateJson.put("unit_id", unitId);
            updateJson.put("deep_conversion_bid", deepConversionBid);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.UPDATE_UNIT;
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", accessToken);
            headers.put("Content-Type", "application/json");
            String result = HttpUtils.kuaiShouhttpPostRequest(url, updateJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            log.info("修改深度转化出价返回信息，accountId:{},返回信息：{}", accountId, resultJson);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    /*QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("unit_id", unitId);
                    queryWrapper.eq("account_id", advertiserId);
                    queryWrapper.orderByDesc("create_time");
                    queryWrapper.last("limit 1");
                    KuaiShouGroup group = groupMapper.selectOne(queryWrapper);

                    KuaiShouGroupBid groupBid = new KuaiShouGroupBid();
                    groupBid.setAccountId(advertiserId);
                    groupBid.setUnitId(unitId);
                    groupBid.setBid(group.getBid());
                    groupBid.setUpdateBid(bid);
                    groupBid.setUserId(loginId);
                    int i = groupBidMapper.insert(groupBid);
                    if (i > 0) {
                        log.info("修改广告组深度转化出价本地记录添加成功，unitId：{}", unitId);
                    }*/
                    // 重新请求数据

                    returnMap.put("code", 0);
                    returnMap.put("success", true);
                } else {
                    log.error("修改广告组深度转化出价失败，advertiserId：{}，unitId：{}，返回信息：{}", accountId, unitId, resultJson);
                    returnMap.put("code", -1);
                    returnMap.put("success", false);
                    returnMap.put("message", resultJson.getString("message"));
                }
            } else {
                log.error("修改广告组深度转化出价返回结果为空，advertiserId：{}，unitId：{}", returnMap, unitId);
                returnMap.put("code", -1);
                returnMap.put("success", false);
                returnMap.put("message", "修改广告组预算返回结果为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("code", -1);
            returnMap.put("message", e.getMessage());
        }


        return returnMap;
    }

}
