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

import cn.com.ctop.common.module.mapper.KuaiShouOcpxActionTypeConfigMapper;
import cn.com.ctop.common.module.service.IMessageTemplate;
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.batch.entity.KuaiShouAppInfo;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCampaign;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCreative;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroup;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroupTarget;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouSchedule;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouAppInfoMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupTargetMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouScheduleMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCampaignService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouCreativeService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupService;
import cn.com.ctop.kuaishou.modules.batch.service.IWarningOperationService;
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.xxl.job.core.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description: 广告组信息
 * @Author: jeecg-boot
 * @Date: 2019-07-23
 * @Version: V1.0
 */

@Slf4j
@Service
public class KuaiShouGroupServiceImpl extends ServiceImpl<KuaiShouGroupMapper, KuaiShouGroup> implements IKuaiShouGroupService {
    @Autowired
    private IKuaiShouCampaignService kuaiShouCampaignService;
    @Autowired
    private KuaiShouGroupMapper groupMapper;
    @Autowired
    private KuaiShouAppInfoMapper appInfoMapper;
    @Autowired
    private KuaiShouScheduleMapper shouScheduleMapper;
    @Autowired
    private KuaiShouGroupTargetMapper groupTargetMapper;
    private static ExecutorService executorService = Executors.newFixedThreadPool(10);
    @Autowired
    private IKuaiShouCreativeService creativeService;
    @Autowired
    private KuaiShouOcpxActionTypeConfigMapper ocpxActionTypeConfigMapper;
    @Autowired
    private IMessageTemplate messageTemplate;

    /**
     * 获取广告组
     *
     * @param accessToken
     * @param accountId
     */
    @Override
    public void getGroupList(String accessToken, Long accountId) {
        QueryWrapper<KuaiShouCampaign> campaignQueryWrapper = new QueryWrapper<>();
        campaignQueryWrapper.eq("account_id", accountId);
        /*campaignQueryWrapper.eq("status", 4);
        campaignQueryWrapper.eq("put_status", 1);*/
        campaignQueryWrapper.orderByDesc("put_create_time");
        campaignQueryWrapper.last("limit 15");
        List<KuaiShouCampaign> list = kuaiShouCampaignService.list(campaignQueryWrapper);
        if (Check.isNull(list)) {
            return;
        }
        for (KuaiShouCampaign campaign : list) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    getGroupListByPage(accessToken, accountId, campaign.getCampaignId(), 1);
                }
            });
        }


    }

    @Override
    public void getGroupListByPage(String accessToken, Long accountId, Long campaignId, int page) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GROUP_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        if (!Check.isNull(campaignId)) {
            param.put("campaign_id", campaignId);
        }
        param.put("page_size", 500);
        param.put("page", page);

        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)) {
            log.error("获取广告组接口异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告组返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        addGroupV2(accountId, details);
        getGroupListByPage(accessToken, accountId, campaignId, page + 1);
    }

    @Override
    public List<KuaiShouGroup> queryUnitInfoByCampaignId(Long accountId, Long campaignId) {
        return groupMapper.queryUnitInfoByCampaignId(accountId, campaignId);
    }

    @Override
    public KuaiShouGroup selectGroupByUnitId(Long accountId, Long unitId) {
        QueryWrapper<KuaiShouGroup> groupQueryWrapper = new QueryWrapper<>();
        groupQueryWrapper.eq("account_id", accountId);
        groupQueryWrapper.eq("unit_id", unitId);
        groupQueryWrapper.orderByDesc("create_time");
        groupQueryWrapper.last("limit 1");
        KuaiShouGroup group = groupMapper.selectOne(groupQueryWrapper);
        return group;
    }

    @Override
    public Integer queryToDayBuiltCount(Long accountId, Integer unitType) {
        String date = DateUtil.formatDate(new Date());
        return groupMapper.queryToDayBuiltCount(accountId, date, unitType);
    }

    @Override
    public void deleteByAccountId(Long accountId) {
        groupMapper.deleteByAccountId(accountId);
    }

    @Override
    public Integer getNewDataByAccountIdAndDate(Long accountId, String statDate) {
        return groupMapper.getNewDataByAccountIdAndDate(accountId, statDate);
    }

    @Override
    public Map<Long, JSONObject> getBidMapByMap(Long accountId, Map<Long, Long> unitIdMap) {
        Map<Long, JSONObject> unitMap = new HashMap<>();
        if (Check.isNullMap(unitIdMap)) {
            return unitMap;
        }
        List<JSONObject> unitList = groupMapper.getUnitListByMapAndAccountId(unitIdMap, accountId);
        if (Check.isNull(unitList)) {
            return unitMap;
        }
        for (int i = 0; i < unitList.size(); i++) {
            JSONObject jsonObject = unitList.get(i);
            unitMap.put(jsonObject.getLong("unitId"), jsonObject);
        }

        return unitMap;
    }


    @Override
    public void getGroupByUnitId(String accessToken, Long accountId, Long unitId) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.GROUP_LIST;
        JSONObject param = new JSONObject();
        param.put("advertiser_id", accountId);
        param.put("unit_id", unitId);

        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)) {
            log.error("获取广告组接口异常,advertiserId:{}", accountId);
            return;
        }
        Integer code = resultJson.getInteger("code");
        if (null == code || code != 0) {
            log.error("获取广告组返回结果异常,advertiserId:{},异常信息:{}", accountId, resultJson);
            return;
        }
        JSONArray details = resultJson.getJSONObject("data").getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        addGroupV2(accountId, details);
    }


    /**
     * 根据组获取创意
     *
     * @param accessToken
     * @param accountId
     * @param unitId
     */
    @Override
    public void getCreativeByUnit(String accessToken, Long accountId, Long unitId) {

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


            param.put("unit_id", unitId);
            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;
            }
            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.setCreativeCategory(detailJson.getInteger("creative_category"));
                    if (!Check.isNull(detailJson.getJSONArray("creative_tag"))) {
                        creative.setCreativeTag(detailJson.getJSONArray("creative_tag").toJSONString());
                    }
                    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);
                }
            }

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

        }


    }

    @Override
    public List<KuaiShouGroup> queryUnitInfoByAccountId(Long accountId) {
        return groupMapper.queryUnitInfoByAccountId(accountId);
    }

    @Override
    public void delAllGroupByCampaignId(Long accountId, Long campaignId) {
        groupMapper.delAllGroupByCampaignId(accountId, campaignId);
    }

    static ExecutorService executorBidTypeService = Executors.newFixedThreadPool(20);
    static ExecutorService executorMaxBidService = Executors.newFixedThreadPool(5);
    @Autowired
    private IWarningOperationService warningOperationService;

    private void addGroupV2(Long advertiserId, JSONArray details) {

        JSONObject json = warningOperationService.getBidTypeAndMaxBid(advertiserId);
        if (Check.isNull(json) || Check.isNull(details)) {
            return;
        }

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

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

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

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

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

                        Boolean typeFalg = true;
                        Boolean bidFalg = true;

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

                        //转化目标
                        if (!Check.isNull(deepConversionType) && deepConversionType != 0 && !deepMap.isEmpty()) {
                            String msg = Check.isNull(textMap.get(deepConversionType)) ? String.valueOf(deepConversionType) : textMap.get(deepConversionType);
                            Long deepBid = deepMap.get(deepConversionType);
                            if (Check.isNull(deepBid)) {
                                //通过key未获取值，说明不包含该目标，进行关停
                                typeFalg = false;
                                msgType = "组深度转化目标：" + msg;
                            } else {
                                if (deepConversionBid > deepBid) {
                                    //组深度转化出价 大于 项目设置最大转化出价，则关停
                                    bidFalg = false;
                                    msgBid = "深度转化出价：" + deepConversionBid + " > 项目出价：" + deepBid;
                                }
                            }
                        }
                        String typeText = messageTemplate.getKuaiShouBidTypeMessage(json.getString("projectName"), advertiserId, unitId, unitName, msgType);
                        String bidText = messageTemplate.getKuaiShouBidMessage(json.getString("projectName"), advertiserId, unitId, unitName, msgBid);

                        if (!typeFalg) { // 出价方式设置非法
                            executorBidTypeService.submit(new Runnable() {
                                @Override
                                public void run() {
                                    warningOperationService.kuaiShouWarningOperation(json.getLong("projectId"), typeText, advertiserId, unitId, unitName);
                                }
                            });
                        }
                        if (!bidFalg) {
                            executorMaxBidService.submit(new Runnable() {
                                @Override
                                public void run() {
                                    warningOperationService.kuaiShouBidWarningOperation(json.getLong("projectId"), bidText, advertiserId, unitId, unitName);
                                }
                            });
                        }
                    }

                    KuaiShouGroup group = JSONObject.parseObject(detail.toJSONString(), KuaiShouGroup.class);
                    group.setId("" + advertiserId + unitId);
                    group.setAccountId(advertiserId);
                    group.setGroupCreateTime(detail.getString("create_time"));
                    group.setGroupUpdateTime(detail.getString("update_time"));
                    group.setCreateTime(new Date());
                    group.setUpdateTime(new Date());
                    groups.add(group);

                    // 添加应用信息
                    JSONObject diverseJson = detail.getJSONObject("diverse_data");
                    if (!Check.isNull(diverseJson)) {
                        KuaiShouAppInfo appInfo = new KuaiShouAppInfo();
                        appInfo.setAccountId(advertiserId);
                        appInfo.setAppName(diverseJson.getString("app_name"));
                        appInfo.setAppPackageName(diverseJson.getString("app_package_name"));
                        appInfo.setDeviceOsType(diverseJson.getInteger("device_os_type"));
                        appInfo.setUnitId(unitId);
                        appInfo.setCreateTime(new Date());
                        appInfo.setUpdateTime(new Date());
                        appInfos.add(appInfo);
                    }
                    //时间段信息
                    JSONObject scheduleJson = detail.getJSONObject("schedule");
                    if (!Check.isNull(scheduleJson)) {
                        KuaiShouSchedule schedule = new KuaiShouSchedule();
                        schedule.setUnitId(unitId);
                        schedule.setAccountId(advertiserId);
                        schedule.setMon(scheduleJson.getJSONArray("mon").toJSONString());
                        schedule.setTues(scheduleJson.getJSONArray("tues").toJSONString());
                        schedule.setWed(scheduleJson.getJSONArray("wed").toJSONString());
                        schedule.setThur(scheduleJson.getJSONArray("thur").toJSONString());
                        schedule.setFri(scheduleJson.getJSONArray("fri").toJSONString());
                        schedule.setSat(scheduleJson.getJSONArray("sat").toJSONString());
                        schedule.setSun(scheduleJson.getJSONArray("sun").toJSONString());
                        schedule.setCreateTime(new Date());
                        schedule.setUpdateTime(new Date());
                        schedules.add(schedule);
                    }

                    JSONObject targetJson = detail.getJSONObject("target");
                    if (!Check.isNull(targetJson)) {
                        KuaiShouGroupTarget groupTarget = new KuaiShouGroupTarget();
                        groupTarget.setAccountId(advertiserId);
                        groupTarget.setUnitId(unitId);
                        if (!Check.isNull(targetJson.getJSONArray("region"))) {
                            groupTarget.setRegion(targetJson.getJSONArray("region").toJSONString());
                        }

                        JSONObject age = targetJson.getJSONObject("age");
                        if (!Check.isNull(age)) {
                            groupTarget.setAgeMin(age.getInteger("min"));
                            groupTarget.setAgeMax(age.getInteger("max"));
                        }
                        if (!Check.isNull(targetJson.getJSONArray("ages_range"))) {
                            groupTarget.setAgesRange(targetJson.getJSONArray("ages_range").toJSONString());
                        }

                        groupTarget.setGender(targetJson.getInteger("gender"));
                        groupTarget.setPlatformOs(targetJson.getInteger("platform_os"));
                        groupTarget.setAndroidOsv(targetJson.getInteger("android_osv"));
                        groupTarget.setIosOsv(targetJson.getInteger("ios_osv"));
                        groupTarget.setNetwork(targetJson.getInteger("network"));
                        if (!Check.isNull(targetJson.getJSONArray("device_brand"))) {
                            groupTarget.setDeviceBrand(targetJson.getJSONArray("device_brand").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("device_price"))) {
                            groupTarget.setDevicePrice(targetJson.getJSONArray("device_price").toJSONString());
                        }

                        groupTarget.setBusinessInterestType(targetJson.getInteger("business_interest_type"));
                        if (!Check.isNull(targetJson.getJSONArray("business_interest"))) {
                            groupTarget.setBusinessInterest(targetJson.getJSONArray("business_interest").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("fans_star"))) {
                            groupTarget.setFansStar(targetJson.getJSONArray("fans_star").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("interest_video"))) {
                            groupTarget.setInterestVideo(targetJson.getJSONArray("interest_video").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("app_interest"))) {
                            groupTarget.setAppInterest(targetJson.getJSONArray("app_interest").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("app_ids"))) {
                            groupTarget.setAppIds(targetJson.getJSONArray("app_ids").toJSONString());
                        }


                        if (!Check.isNull(targetJson.getInteger("filter_converted_level"))) {
                            groupTarget.setFilterConvertedLevel(targetJson.getInteger("filter_converted_level"));
                        }


                        if (!Check.isNull(targetJson.getJSONArray("population"))) {
                            groupTarget.setPopulation(targetJson.getJSONArray("population").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("exclude_population"))) {
                            groupTarget.setExcludePopulation(targetJson.getJSONArray("exclude_population").toJSONString());
                        }

                        if (!Check.isNull(targetJson.getJSONArray("third_platform_code"))) {
                            groupTarget.setThirdPlatformCode(targetJson.getJSONArray("third_platform_code").toJSONString());
                        }


                        JSONObject intelliExtend = targetJson.getJSONObject("intelli_extend");
                        if (!Check.isNull(intelliExtend)) {
                            groupTarget.setIsOpen(intelliExtend.getInteger("is_open"));
                            groupTarget.setNoAgeBreak(intelliExtend.getInteger("no_age_break"));
                            groupTarget.setNoGenderBreak(intelliExtend.getInteger("no_gender_break"));
                            groupTarget.setNoAreaBreak(intelliExtend.getInteger("no_area_break"));

                        }
                        //行为兴趣定向
                        JSONObject behaviorInterest = targetJson.getJSONObject("behavior_interest");
                        if (!Check.isNull(behaviorInterest)) {
                            JSONObject behavior = behaviorInterest.getJSONObject("behavior");
                            if (!Check.isNull(behavior)) {
                                if (!Check.isNull(behavior.getJSONArray("keyword"))) {
                                    groupTarget.setKeyword(JSONObject.toJSONString(behavior.getJSONArray("keyword")));
                                }
                                if (!Check.isNull(behavior.getString("label"))) {
                                    groupTarget.setLabel(behavior.getString("label"));
                                }
                                if (!Check.isNull(behavior.getInteger("time_type"))) {
                                    groupTarget.setTimeType(behavior.getInteger("time_type"));
                                }
                                if (!Check.isNull(behavior.getInteger("strength_type"))) {
                                    groupTarget.setStrengthType(behavior.getInteger("strength_type"));
                                }
                                if (!Check.isNull(behavior.getString("scene_type"))) {
                                    groupTarget.setSceneType(behavior.getString("scene_type"));
                                }
                            }
                            JSONObject interest = behaviorInterest.getJSONObject("interest");
                            if (!Check.isNull(interest)) {
                                if (!Check.isNull(interest.getString("label"))) {
                                    groupTarget.setInterestLabel(interest.getString("label"));
                                }
                            }
                        }
                        targets.add(groupTarget);
                    }
                }
            }
            if (!Check.isNull(groups)) {
                groupMapper.replaceBatch(groups);
            }
            if (!Check.isNull(schedules)) {
                shouScheduleMapper.replaceBatch(schedules);
            }
            if (!Check.isNull(appInfos)) {
                appInfoMapper.replaceBatch(appInfos);
            }
            if (!Check.isNull(targets)) {
                groupTargetMapper.replaceBatch(targets);
            }
        }
    }

}
