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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.ISysRoleExtService;
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.entity.KuaishouDirectionalPackage;
import cn.com.ctop.kuaishou.modules.ai.entity.KuaishouDirectionalaPckageRel;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouDirectionalPackageMapper;
import cn.com.ctop.kuaishou.modules.ai.mapper.KuaishouDirectionalPckageRelMapper;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPackageService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouDirectionalPckageRelService;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouMaterialPoolOperationRecordService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplateTarget;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouTemplateMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouTemplateTargetMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupTemplateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouUpdateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 自动投放-定向包详情
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-04-20
 */
@Slf4j
@Service
public class KuaishouDirectionalPackageServiceImpl extends ServiceImpl<KuaishouDirectionalPackageMapper, KuaishouDirectionalPackage> implements IKuaishouDirectionalPackageService {

    @Autowired
    private IKuaishouTemplateService kuaishouTemplateService;
    @Autowired
    private KuaishouDirectionalPackageMapper packageMapper;
    @Autowired
    private KuaishouDirectionalPckageRelMapper relMapper;
    @Autowired
    private IKuaishouDirectionalPckageRelService relService;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Autowired
    private KuaishouTemplateMapper templateMapper;
    @Autowired
    private IKuaiShouUpdateService updateService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private KuaishouTemplateTargetMapper templateTargetMapper;
    @Autowired
    private ISysRoleExtService sysRoleService;
    @Autowired
    private IKuaiShouGroupTemplateService groupTemplateService;
    static ExecutorService executorService = null;
    @Autowired
    private IKuaishouMaterialPoolOperationRecordService kuaishouMaterialPoolOperationRecordService;

    @Override
    public Result<Object> createDirectionalPackage(JSONObject requestJson) {
        KuaishouDirectionalPackage entity = packageMapper.queryEntity(requestJson);
        if (!Check.isNull(entity)) {
            return Result.error("该账户下定向包名已存在");
        }
        KuaishouDirectionalPackage kuaishouDirectionalPackage = JSONObject.toJavaObject(requestJson, KuaishouDirectionalPackage.class);
        if (!Check.isNull(requestJson.getJSONArray("keyword"))) {
            kuaishouDirectionalPackage.setKeyword(JSONObject.toJSONString(requestJson.getJSONArray("keyword")));
        }
        kuaishouDirectionalPackage.setDataStatus(1);
        boolean save = this.save(kuaishouDirectionalPackage);
        if (save) {
            return Result.ok("创建成功");
        }
        return Result.error("创建失败，定向包存储失败");
    }


    @Override
    public Result<Object> updateDirectionalPackage(JSONObject requestJson) throws InterruptedException {
        KuaishouDirectionalPackage entity = packageMapper.selectById(requestJson.getString("id"));
        if (Check.isNull(entity)) {
            return Result.error("未获取到定向包");
        }
        KuaishouDirectionalPackage kuaishouDirectionalPackage = JSONObject.toJavaObject(requestJson, KuaishouDirectionalPackage.class);
        if (!Check.isNull(requestJson.getJSONArray("keyword"))) {
            kuaishouDirectionalPackage.setKeyword(JSONObject.toJSONString(requestJson.getJSONArray("keyword")));
        }
        this.saveOrUpdate(kuaishouDirectionalPackage);
        //获取本项目绑定该定向的账户
        List<JSONObject> accounts = relMapper.queryRelId(requestJson.getLong("projectId"), requestJson.getString("id"), "account");
        if (!Check.isNull(accounts)) {
            for (JSONObject account : accounts) {
                updateAccountsDirectionalPackage(requestJson, account);
            }
        }
        Thread.sleep(300);
        //获取本项目绑定该定向的广告组
        List<JSONObject> units = relMapper.queryRelId(requestJson.getLong("projectId"), requestJson.getString("id"), "unit");
        if (!Check.isNull(units)) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    executorService = Executors.newFixedThreadPool(3);
                    units.forEach(unit -> {
                        executorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    updateUnitsDirectionalPackage(requestJson, unit);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    });
                    log.info("修改广告组定向完成");
                }
            };
            thread.start();
        }
        if (!entity.getTemplateName().equals(kuaishouDirectionalPackage.getTemplateName())) {
            relMapper.updateTemName(entity.getId(), kuaishouDirectionalPackage.getTemplateName());
        }
        return Result.ok("该项目下定向包已做同步修改");
    }

    private void updateUnitsDirectionalPackage(JSONObject requestJson, JSONObject unit) {
        try {
            Long unitId = unit.getLong("rel_id");
            QueryWrapper<KuaiShouGroup> queryWrapper = new QueryWrapper();
            queryWrapper.eq("unit_id", unitId);
            queryWrapper.last("limit 1");
            KuaiShouGroup kuaiShouGroup = groupMapper.selectOne(queryWrapper);
            if (Check.isNull(kuaiShouGroup)) {
                throw new Exception("未获取到组信息");
            }
            CtopOauthToken token = oauthTokenService.getTokenByAccountId(kuaiShouGroup.getAccountId());
            String sceneIdStr = kuaiShouGroup.getSceneId();
            if (Check.isNull(sceneIdStr)) {
                throw new Exception("未获取资源位置");
            }
            Integer sceneId = (Integer) JSONArray.parseArray(sceneIdStr).get(0);
            JSONObject unitJson = new JSONObject();
            unitJson.put("advertiser_id", kuaiShouGroup.getAccountId());
            unitJson.put("unit_id", unitId);
            if (sceneId != 5) {
                unitJson.put("template_id", unit.getLong("template_id"));
            } else {
                JSONObject unionJson = groupTemplateService.getUnionJson(unit.getLong("template_id"));
                if (Check.isNullMap(unionJson)) {
                    throw new Exception("根据定向模板未获取到相关信息");
                }
                unitJson.put("target", unionJson.getJSONObject("target"));
            }
            updateService.updateUnit(token.getAccessToken(), unitJson);
        } catch (Exception e) {
            log.error("修改广告组定向异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 更新帐户定向包
     *
     * @param
     * @return void
     * @throws
     * @author ZHAOXA
     */
    private void updateAccountsDirectionalPackage(JSONObject requestJson, JSONObject accounEntity) {
        Long accountId = accounEntity.getLong("rel_id");
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        try {
            JSONObject param = new JSONObject();
            param.put("template_id", accounEntity.getLong("template_id"));
            param.put("advertiser_id", accountId);
            if (!Check.isNull(requestJson.getString("templateName"))) {
                param.put("template_name", requestJson.getString("templateName"));
            }
            JSONObject targetJson = new JSONObject();
            if (requestJson.getJSONArray("region") != null) {
                targetJson.put("region", requestJson.getJSONArray("region"));
            }
            if (!Check.isNull(requestJson.getJSONArray("districtIds"))) {
                targetJson.put("district_ids", requestJson.getJSONArray("districtIds"));
            }
            if (!Check.isNull(requestJson.getInteger("userType"))) {
                targetJson.put("user_type", requestJson.getInteger("userType"));
            }
            JSONArray agesRange = requestJson.getJSONArray("agesRange");
            if (!Check.isNull(agesRange)) {
                targetJson.put("ages_range", agesRange);
            }
            Integer min = requestJson.getInteger("min");
            Integer max = requestJson.getInteger("max");
            if (!Check.isNull(min) && !Check.isNull(max) && max != -1 && min != -1) {
                JSONObject ageJson = new JSONObject();
                ageJson.put("min", requestJson.getInteger("min"));
                ageJson.put("max", requestJson.getInteger("max"));
                targetJson.put("age", ageJson);
            }

            if (!Check.isNull(requestJson.getInteger("gender"))) {
                targetJson.put("gender", requestJson.getInteger("gender"));
            }
            if (!Check.isNull(requestJson.getInteger("platformOs"))) {
                targetJson.put("platform_os", requestJson.getInteger("platformOs"));
            }
            if (!Check.isNull(requestJson.getInteger("androidOsv"))) {
                targetJson.put("android_osv", requestJson.getInteger("androidOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", requestJson.getInteger("iosOsv"));
            }
            if (!Check.isNull(requestJson.getInteger("network"))) {
                targetJson.put("network", requestJson.getInteger("network"));
            }
            if (!Check.isNull(requestJson.getInteger("filterConvertedLevel"))) {
                targetJson.put("filter_converted_level", requestJson.getInteger("filterConvertedLevel"));
            }
            if (requestJson.getJSONArray("deviceBrand") != null) {
                targetJson.put("device_brand", requestJson.getJSONArray("deviceBrand"));
            }
            if (requestJson.getJSONArray("devicePrice") != null) {
                targetJson.put("device_price", requestJson.getJSONArray("devicePrice"));
            }
            if (!Check.isNull(requestJson.getInteger("businessInterestType"))) {
                targetJson.put("business_interest_type", requestJson.getInteger("businessInterestType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("businessInterest"))) {
                targetJson.put("business_interest", requestJson.getJSONArray("businessInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("fansStar"))) {
                targetJson.put("fans_star", requestJson.getJSONArray("fansStar"));
            }
            if (!Check.isNull(requestJson.getJSONArray("interestVideo"))) {
                targetJson.put("interest_video", requestJson.getJSONArray("interestVideo"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", requestJson.getJSONArray("appInterest"));
            }
            if (!Check.isNull(requestJson.getJSONArray("appIds"))) {
                targetJson.put("app_ids", requestJson.getJSONArray("appIds"));
            }
            if (!Check.isNull(requestJson.getJSONArray("population"))) {
                targetJson.put("population", requestJson.getJSONArray("population"));
            }
            if (!Check.isNull(requestJson.getJSONArray("paidAudience"))) {
                targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
            }
            if (!Check.isNull(requestJson.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            }
            if (!Check.isNull(requestJson.getInteger("isOpen"))) {
                JSONObject intelliExtendJson = new JSONObject();
                intelliExtendJson.put("is_open", requestJson.getInteger("isOpen"));

                if (!Check.isNull(requestJson.getInteger("noAgeBreak"))) {
                    intelliExtendJson.put("no_age_break", requestJson.getInteger("noAgeBreak"));
                }
                if (!Check.isNull(requestJson.getInteger("noGenderBreak"))) {
                    intelliExtendJson.put("no_gender_break", requestJson.getInteger("noGenderBreak"));
                }
                if (!Check.isNull(requestJson.getInteger("noAreaBreak"))) {
                    intelliExtendJson.put("no_area_break", requestJson.getInteger("noAreaBreak"));
                }
                if (!Check.isNull(intelliExtendJson)) {
                    targetJson.put("intelli_extend", intelliExtendJson);
                }
            }
            JSONObject behaviorInterest = new JSONObject();
            JSONObject behavior = new JSONObject();
            JSONObject interest = new JSONObject();
            if (!Check.isNull(requestJson.getJSONArray("keyword"))) {
                behavior.put("keyword", requestJson.getJSONArray("keyword"));
            }
            if (!Check.isNull(requestJson.getJSONArray("label"))) {
                behavior.put("label", requestJson.getJSONArray("label"));
            }
            if (!Check.isNull(requestJson.getInteger("strengthType"))) {
                behavior.put("strength_type", requestJson.getInteger("strengthType"));
            }
            if (!Check.isNull(requestJson.getInteger("timeType"))) {
                behavior.put("time_type", requestJson.getInteger("timeType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("sceneType"))) {
                behavior.put("scene_type", requestJson.getJSONArray("sceneType"));
            }
            if (!Check.isNull(requestJson.getJSONArray("interestLabel"))) {
                interest.put("label", requestJson.getJSONArray("interestLabel"));
            }
            if (!behavior.isEmpty()) {
                behaviorInterest.put("behavior", behavior);
            }
            if (!interest.isEmpty()) {
                behaviorInterest.put("interest", interest);
            }
            if (!behaviorInterest.isEmpty()) {
                targetJson.put("behavior_interest", behaviorInterest);
            }
            if (!Check.isNull(targetJson)) {
                param.put("target", targetJson);
            }
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", oauthToken.getAccessToken());
            headers.put("Content-Type", " application/json");
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_UPDATE;
            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) {
                    kuaishouTemplateService.getTemplateByAccountId(accountId, oauthToken.getAccessToken(), 1);
                } else {
                    log.error("修改账户定向失败，" + resultJson.getString("message"));
                }
            }
        } catch (Exception e) {
            log.error("修改账户定向包异常，账户Id:{}", accountId, e);
        }
    }

    @Override
    public Result<Object> queryList(KuaishouDirectionalPackage directionalPackage, Integer pageNo, Integer pageSize) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = null;
        if (!Check.isNull(user)) {
            userId = user.getId();
            String roleCode = sysRoleService.getRoleCodeByUserId(userId);
            //角色为管理员、销售、媒介可以查看所有项目信息
            if ("admin".equals(roleCode) || roleCode.contains("sale") || "meidaManager".equals(roleCode)) {
                userId = null;
            }
        }
        directionalPackage.setUserId(userId);
        Long total = packageMapper.queryListTotal(directionalPackage);
        PageHelper.startPage(pageNo, pageSize, false);
        List<JSONObject> list = packageMapper.queryList(directionalPackage);
        PageInfo pageInfo = new PageInfo(list);
        pageInfo.setTotal(total);
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> getRelatedAccountGroup(String id, Integer type, Long accountId, Integer pageNo, Integer pageSize) {
        PageInfo pageInfo = null;
        if (1 == type) {
            PageHelper.startPage(pageNo, pageSize);
            pageInfo = new PageInfo(packageMapper.getRelatedAccount(id));
        } else {
            PageHelper.startPage(pageNo, pageSize);
            pageInfo = new PageInfo(packageMapper.getRelatedGroup(id, accountId));
        }
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> pushDirectionalPackage(String id, JSONArray datas, JSONObject requestJson) {
        KuaishouDirectionalPackage directionalPackage = packageMapper.selectById(id);
        if (Check.isNull(directionalPackage)) {
            return Result.error("未获取到定向信息");
        }
        requestJson.put("projectId", directionalPackage.getProjectId());
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(directionalPackage)).toJavaObject(JSONObject.class);
        if (Check.isNull(data)) {
            return Result.error("未找到定向包");
        }
        for (int i = 0; i < datas.size(); i++) {
            JSONObject request = datas.getJSONObject(i);
            createDirectionalPackage2(data, request);
        }
        kuaishouMaterialPoolOperationRecordService.addRecord(requestJson, "/pushDirectionalPackage", 1, "push");
        return Result.ok("推送完成");
    }

    @Override
    public void createDirectionalPackage2(JSONObject data, JSONObject request) {
        Long accountId = request.getLong("accountId");
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        String message = "";
        KuaishouDirectionalaPckageRel rel = new KuaishouDirectionalaPckageRel();
        rel.setDirId(data.getString("id"));
        rel.setRelId(accountId);
        rel.setRelType("account");
        rel.setProjectId(data.getLong("projectId"));
        rel.setTemplateName(data.getString("templateName"));
        rel.setDataStatus(0);
        try {
            JSONObject param = new JSONObject();
            param.put("advertiser_id", accountId);
            param.put("template_name", data.getString("templateName"));
            JSONObject targetJson = new JSONObject();
            if (data.getJSONArray("region") != null) {
                targetJson.put("region", data.getJSONArray("region"));
            }
            if (!Check.isNull(data.getJSONArray("districtIds"))) {
                targetJson.put("district_ids", data.getJSONArray("districtIds"));
            }
            if (!Check.isNull(data.getInteger("userType"))) {
                targetJson.put("user_type", data.getInteger("userType"));
            }
            if (!Check.isNull(data.getJSONArray("agesRange"))) {
                targetJson.put("ages_range", data.getJSONArray("agesRange"));
            }

            Integer min = data.getInteger("min");
            Integer max = data.getInteger("max");
            if (!Check.isNull(min) && !Check.isNull(max) && max != -1 && min != -1) {
                JSONObject ageJson = new JSONObject();
                ageJson.put("min", data.getInteger("min"));
                ageJson.put("max", data.getInteger("max"));
                targetJson.put("age", ageJson);
            }

            if (!Check.isNull(data.getInteger("gender"))) {
                targetJson.put("gender", data.getInteger("gender"));
            }
            if (!Check.isNull(data.getInteger("platformOs"))) {
                targetJson.put("platform_os", data.getInteger("platformOs"));
            }
            if (!Check.isNull(data.getInteger("androidOsv"))) {
                targetJson.put("android_osv", data.getInteger("androidOsv"));
            }
            if (!Check.isNull(data.getInteger("iosOsv"))) {
                targetJson.put("ios_osv", data.getInteger("iosOsv"));
            }
            if (!Check.isNull(data.getInteger("network"))) {
                targetJson.put("network", data.getInteger("network"));
            }
            if (!Check.isNull(data.getInteger("filterConvertedLevel"))) {
                targetJson.put("filter_converted_level", data.getInteger("filterConvertedLevel"));
            }
            if (data.getJSONArray("deviceBrand") != null) {
                targetJson.put("device_brand", data.getJSONArray("deviceBrand"));
            }
            if (data.getJSONArray("devicePrice") != null) {
                targetJson.put("device_price", data.getJSONArray("devicePrice"));
            }
            if (!Check.isNull(data.getInteger("businessInterestType"))) {
                targetJson.put("business_interest_type", data.getInteger("businessInterestType"));
            }
            if (!Check.isNull(data.getJSONArray("businessInterest"))) {
                targetJson.put("business_interest", data.getJSONArray("businessInterest"));
            }
            if (!Check.isNull(data.getJSONArray("fansStar"))) {
                targetJson.put("fans_star", data.getJSONArray("fansStar"));
            }
            if (!Check.isNull(data.getJSONArray("interestVideo"))) {
                targetJson.put("interest_video", data.getJSONArray("interestVideo"));
            }
            if (!Check.isNull(data.getJSONArray("appInterest"))) {
                targetJson.put("app_interest", data.getJSONArray("appInterest"));
            }
            if (!Check.isNull(data.getJSONArray("appIds"))) {
                targetJson.put("app_ids", data.getJSONArray("appIds"));
            }
            if (!Check.isNull(request.getJSONArray("population"))) {
                targetJson.put("population", request.getJSONArray("population"));
                rel.setPopulation(request.getString("population"));
            }
            if (!Check.isNull(request.getJSONArray("paidAudience"))) {
                targetJson.put("paid_audience", request.getJSONArray("paidAudience"));
                rel.setPaidAudience(request.getString("paidAudience"));
            }
            if (!Check.isNull(request.getJSONArray("excludePopulation"))) {
                targetJson.put("exclude_population", request.getJSONArray("excludePopulation"));
                rel.setExcludePopulation(request.getString("excludePopulation"));
            }
            if (!Check.isNull(data.getInteger("isOpen"))) {
                JSONObject intelliExtendJson = new JSONObject();
                intelliExtendJson.put("is_open", data.getInteger("isOpen"));

                if (!Check.isNull(data.getInteger("noAgeBreak"))) {
                    intelliExtendJson.put("no_age_break", data.getInteger("noAgeBreak"));
                }
                if (!Check.isNull(data.getInteger("noGenderBreak"))) {
                    intelliExtendJson.put("no_gender_break", data.getInteger("noGenderBreak"));
                }
                if (!Check.isNull(data.getInteger("noAreaBreak"))) {
                    intelliExtendJson.put("no_area_break", data.getInteger("noAreaBreak"));
                }
                if (!Check.isNull(intelliExtendJson)) {
                    targetJson.put("intelli_extend", intelliExtendJson);
                }
            }
            //-------------兴趣行为定向
            JSONObject behaviorInterest = new JSONObject();
            JSONObject behavior = new JSONObject();
            JSONObject interest = new JSONObject();
            if (!Check.isNull(data.getJSONArray("keyword"))) {
                behavior.put("keyword", data.getJSONArray("keyword"));
            }
            if (!Check.isNull(data.getJSONArray("label"))) {
                behavior.put("label", data.getJSONArray("label"));
            }
            if (!Check.isNull(data.getInteger("strengthType"))) {
                behavior.put("strength_type", data.getInteger("strengthType"));
            }
            if (!Check.isNull(data.getInteger("timeType"))) {
                behavior.put("time_type", data.getInteger("timeType"));
            }
            if (!Check.isNull(data.getJSONArray("sceneType"))) {
                behavior.put("scene_type", data.getJSONArray("sceneType"));
            }
            if (!Check.isNull(data.getJSONArray("interestLabel"))) {
                interest.put("label", data.getJSONArray("interestLabel"));
            }
            if (!behavior.isEmpty()) {
                behaviorInterest.put("behavior", behavior);
            }
            if (!interest.isEmpty()) {
                behaviorInterest.put("interest", interest);
            }
            if (!behaviorInterest.isEmpty()) {
                targetJson.put("behavior_interest", behaviorInterest);
            }
            if (!Check.isNull(targetJson)) {
                param.put("target", targetJson);
            }
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", oauthToken.getAccessToken());
            headers.put("Content-Type", " application/json");
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_CREATE;
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                message = resultJson.getString("message");
                if (code == 0) {
                    kuaishouTemplateService.getTemplateByAccountId(accountId, oauthToken.getAccessToken(), 1);
                    JSONObject results = resultJson.getJSONObject("data");
                    rel.setTemplateId(results.getLong("template_id"));
                    rel.setDataStatus(1);
                } else {
                    message = "推送定向包失败，" + message;
                    log.error(message);
                }
            } else {
                message = "推送定向包失败，返回结果为空";
            }
        } catch (Exception e) {
            message = "推送定向包出现异常";
            log.error(message, e);
        }
        rel.setMessage(message);
        relMapper.replace(rel);
    }

    @Override
    public Result<Object> queryPushResults(String id, JSONArray accountIds, String status) {
        List<JSONObject> list = relMapper.queryPushResults(id, accountIds, status);
        return Result.ok(new PageInfo<>(list));
    }


    @Override
    public Result<Object> editPopulation(JSONObject requestJson) {
        Long accountId = requestJson.getLong("accountId");
        String message = "";
        KuaishouDirectionalaPckageRel rel = new KuaishouDirectionalaPckageRel();
        try {
            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
            QueryWrapper<KuaishouDirectionalaPckageRel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dir_id", requestJson.getString("id"));
            queryWrapper.eq("rel_id", accountId);
            queryWrapper.eq("rel_type", "account");
            queryWrapper.eq("template_id", requestJson.getLong("templateId"));
            JSONObject param = new JSONObject();
            param.put("template_id", requestJson.getLong("templateId"));
            param.put("advertiser_id", accountId);
            param.put("template_name", requestJson.getString("templateName"));
            JSONObject targetJson = new JSONObject();
            targetJson.put("population", requestJson.getJSONArray("population"));
            rel.setPopulation(requestJson.getString("population"));
            targetJson.put("paid_audience", requestJson.getJSONArray("paidAudience"));
            rel.setPaidAudience(requestJson.getString("paidAudience"));
            targetJson.put("exclude_population", requestJson.getJSONArray("excludePopulation"));
            rel.setExcludePopulation(requestJson.getString("excludePopulation"));
            if (!Check.isNull(targetJson)) {
                param.put("target", targetJson);
            }
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Access-Token", oauthToken.getAccessToken());
            headers.put("Content-Type", " application/json");
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_UPDATE;
            String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                message = resultJson.getString("message");
                if (code == 0) {
                    kuaishouTemplateService.getTemplateByAccountId(requestJson.getLong("accountId"), oauthToken.getAccessToken(), 1);
                    JSONObject data = resultJson.getJSONObject("data");
                    relService.update(rel, queryWrapper);
                    List<JSONObject> units = relMapper.queryUnitIdByAccountId(requestJson.getString("id"), requestJson.getLong("accountId"));
                    for (JSONObject unit : units) {
                        updateUnitsDirectionalPackage(requestJson, unit);
                    }
                    return Result.ok("修改成功");
                } else {
                    return Result.error("修改失败，" + message);
                }
            } else {
                return Result.error("修改失败，返回结果为空");
            }
        } catch (Exception e) {
            log.error("修改定向模板人群包信息异常，账户：{}", accountId, e.getMessage());
            e.printStackTrace();
        }
        return Result.error("修改失败");
    }

    @Override
    public Result<Object> getAccountByProjectId(Long projectId, String id) {
        List<JSONObject> list = relMapper.getAccountByProjectId(projectId, id);
        return Result.ok(new PageInfo<>(list));
    }

    @Override
    public void createUnitAndTemplate(JSONObject request) throws Exception {
        try {
            JSONObject target = templateMapper.queryByTemplateId(request.getLong("templateId"));
            if (Check.isNull(target)) {
                throw new Exception("添加广告组和定向模板绑定关系失败");
            }
            KuaishouDirectionalaPckageRel relEntity = new KuaishouDirectionalaPckageRel();
            relEntity.setDirId(target.getString("dir_id"));
            relEntity.setProjectId(target.getLong("project_id"));
            relEntity.setTemplateId(request.getLong("templateId"));
            relEntity.setTemplateName(target.getString("template_name"));
            relEntity.setDataStatus(1);
            relEntity.setRelId(request.getLong("unitId"));
            relEntity.setRelType("unit");
            relEntity.setExcludePopulation(request.getString("excludePopulation"));
            relEntity.setPopulation(request.getString("population"));
            relEntity.setPaidAudience(request.getString("paidAudience"));
            relMapper.replace(relEntity);
        } catch (Exception e) {
            log.error("添加广告组和定向模板绑定关系异常", e);
        }
    }

    @Override
    public Result<Object> queryPopulationById(Long templateId, Long accountId) {
        KuaishouTemplateTarget target = templateTargetMapper.queryTemplateTarget(templateId, accountId);
        if (Check.isNull(target)) {
            return Result.error("未查询到人群包");
        }
        JSONObject data = new JSONObject();
        String excludePopulation = target.getExcludePopulation();
        if (!Check.isNull(excludePopulation)) {
            data.put("excludePopulation", JSONArray.parseArray(excludePopulation));
        }
        String population = target.getPopulation();
        if (!Check.isNull(population)) {
            data.put("population", JSONArray.parseArray(population));
        }
        String paidAudience = target.getPaidAudience();
        if (!Check.isNull(paidAudience)) {
            data.put("paidAudience", JSONArray.parseArray(paidAudience));
        }
        return Result.ok(data);
    }

    @Override
    public Result<Object> getProjectTarget(Long projectId, String templateName, Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<KuaishouDirectionalPackage> list = packageMapper.queryListByProjectId(projectId, templateName);
        return Result.ok(new PageInfo(list));
    }

    @Override
    public List<KuaishouDirectionalPackage> getProjectTargetByIds(List<String> ids) {
        return packageMapper.getProjectTargetByIds(ids);
    }

    @Override
    public Long selectTemplateId(String id, Long accountId) {
        return relMapper.selectTemplateId(id, accountId);
    }

}
