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

import cn.com.ctop.common.module.enums.SceneIdEnum;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouAppList;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouCampaign;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCampaignPreview;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCreativePreview;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchGroupPreview;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplate;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCampaignMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCampaignPreviewMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCreativePreviewMapper;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchGroupPreviewMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouAppListService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouBatchCampaignPreviewService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateService;
import com.alibaba.excel.util.CollectionUtils;
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.enums.NoEn;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 快手-广告计划预览信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-01-26
 */
@Service
public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<KuaishouBatchCampaignPreviewMapper, KuaishouBatchCampaignPreview> implements IKuaishouBatchCampaignPreviewService {
    @Resource
    KuaishouBatchCampaignPreviewMapper campaignPreviewMapper;
    @Resource
    KuaishouBatchGroupPreviewMapper groupPreviewMapper;
    @Resource
    KuaishouBatchCreativePreviewMapper creativePreviewMapper;
    @Autowired
    private IKuaishouTemplateService kuaishouTemplateService;
    @Autowired
    private IKuaiShouAppListService kuaiShouAppListService;
    @Resource
    private KuaiShouCampaignMapper kuaiShouCampaignMapper;

    @Override
    public JSONObject queryByBatchId(String batchId, String accountId) {
        JSONObject obj = new JSONObject();
        QueryWrapper<KuaishouBatchCampaignPreview> campaignWrapper = new QueryWrapper<>();
        campaignWrapper.eq("batch_id", batchId).eq("account_id", accountId).orderByDesc("create_time");
        List<KuaishouBatchCampaignPreview> campaignPreviewList = campaignPreviewMapper.selectList(campaignWrapper);
        QueryWrapper<KuaishouBatchGroupPreview> groupWrapper = new QueryWrapper<>();
        groupWrapper.eq("batch_id", batchId).eq("account_id", accountId).orderByDesc("create_time");
        List<KuaishouBatchGroupPreview> groupPreviewList = groupPreviewMapper.selectList(groupWrapper);
        QueryWrapper<KuaishouBatchCreativePreview> creativeWrapper = new QueryWrapper<>();
        creativeWrapper.eq("batch_id", batchId).eq("account_id", accountId).orderByDesc("create_time");
        List<KuaishouBatchCreativePreview> creativePreviewList = creativePreviewMapper.selectList(creativeWrapper);
        obj.put("campaignList", getCampaignList(campaignPreviewList, groupPreviewList, creativePreviewList));
        return obj;
    }

    /**
     * 获取活动列表
     *
     * @param
     * @return java.util.List<cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCampaignPreview>
     * @throws
     * @author ZHAOXA
     */
    private List<KuaishouBatchCampaignPreview> getCampaignList(List<KuaishouBatchCampaignPreview> campaignPreviewList, List<KuaishouBatchGroupPreview> kuaishouBatchGroupPreviews, List<KuaishouBatchCreativePreview> kuaishouBatchCreativePreviews) {
        List<KuaishouBatchGroupPreview> groups = new ArrayList<>();

        for (KuaishouBatchGroupPreview groupPreview : kuaishouBatchGroupPreviews) {
            JSONArray materialArr = new JSONArray();
            JSONArray descriptionArr = new JSONArray();
            for (KuaishouBatchCreativePreview creativePreview : kuaishouBatchCreativePreviews) {
                if (groupPreview.getPlanId().equals(creativePreview.getPlanId()) && creativePreview.getGroupId().equals(groupPreview.getId())) {
                    JSONObject obj = new JSONObject();
                    obj.put("photoId", creativePreview.getPhotoId());
                    obj.put("imageUrl", creativePreview.getImageUrl());
                    materialArr.add(obj);
                    descriptionArr.add(creativePreview.getDescription());
                    groupPreview.setSiteId(creativePreview.getSiteId());
                    groupPreview.setClickTrackUrl(creativePreview.getClickTrackUrl());
                    groupPreview.setActionbarClickUrl(creativePreview.getActionbarClickUrl());
                }
            }
            QueryWrapper<KuaishouTemplate> queryWrapper = new QueryWrapper();
            queryWrapper.eq("template_id", groupPreview.getTemplateId());
            KuaishouTemplate template = kuaishouTemplateService.getOne(queryWrapper);
            if (!Check.isNull(template)) {
                groupPreview.setTemplateName(template.getTemplateName());
            }
            groupPreview.setMaterialArr(materialArr);
            groupPreview.setDescriptionArr(descriptionArr);
            groups.add(groupPreview);
        }
        List<KuaishouBatchCampaignPreview> campaigns = new ArrayList<>();
        for (KuaishouBatchCampaignPreview campaignPreview : campaignPreviewList) {
            List<KuaishouBatchGroupPreview> groupList = new ArrayList<>();
            for (KuaishouBatchGroupPreview group : groups) {
                if (campaignPreview.getId().equals(group.getPlanId())) {
                    groupList.add(group);
                }
            }
            campaignPreview.setKuaishouBatchGroupPreviews(groupList);
            campaigns.add(campaignPreview);
        }
        return campaigns;
    }

    @Override
    public List<KuaishouBatchCampaignPreview> queryListByTime() {
        return campaignPreviewMapper.queryListByTime();
    }

    /**
     * 添加预览数据
     *
     * @param
     * @return void
     * @throws
     * @author ZHAOXA
     */
    @Override
    public void addPreviewData(JSONObject data) throws Exception {
        String batchId = data.getString("batchId");
        if (Check.isNull(batchId)) {
            throw new Exception("数据异常，未获取到批次标识");
        }
        //计划
        JSONObject campaignJson = data.getJSONObject("campaignJson");
        if (Check.isNull(campaignJson)) {
            throw new Exception("数据异常，未获取到广告计划数据");
        }
        //组
        JSONObject groupJson = data.getJSONObject("unitJson");
        if (Check.isNull(groupJson)) {
            throw new Exception("数据异常，未获取到广告组数据");
        }
        KuaishouBatchGroupPreview groupPreview = commonGroup(groupJson, batchId, campaignJson);
        //创意
        JSONObject creativeJson = data.getJSONObject("creativeJson");
        if (Check.isNull(creativeJson)) {
            throw new Exception("数据异常，未获取到广告创意数据");
        }
        KuaishouBatchCreativePreview creativePreview = commonCreative(creativeJson, batchId);
        //素材数据
        JSONObject materialArray = data.getJSONObject("materialArray");
        if (Check.isNull(materialArray)) {
            throw new Exception("数据异常，未获取到素材数据");
        }
        //创意组
        JSONArray materialList = materialArray.getJSONArray("materialList");
        if (Check.isNull(materialList)) {
            throw new Exception("数据异常，未获取到创意组数据");
        }
        //应用数据
        JSONObject appList = data.getJSONObject("appList");
        if (Check.isNull(appList)) {
            throw new Exception("数据异常，未获取到应用数据");
        }
        //定向包
        JSONArray targetIds = data.getJSONArray("targetIds");
        if (Check.isNull(targetIds)) {
            throw new Exception("数据异常，未获取到应用数据");
        }
        Long campaignId = campaignJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            //分组规则 1 定向 2 创意 3 落地页
            Integer type = campaignJson.getInteger("groupRule");
            KuaishouBatchCampaignPreview campaignPreview = commonCampaign(campaignJson, batchId);
            insertCampaignsAndGroups(type, campaignId, data, campaignPreview, groupPreview, creativePreview);
        } else {
            KuaishouBatchCampaignPreview campaignPreview = getOldCampaign(campaignId, batchId);
            insertCampaignsAndGroups(1, campaignId, data, campaignPreview, groupPreview, creativePreview);
        }
    }

    /**
     * 给已有计划添加数据
     *
     * @param
     * @return void
     * @throws
     * @author ZHAOXA
     */
    private KuaishouBatchCampaignPreview getOldCampaign(Long campaignId, String batchId) throws Exception {
        QueryWrapper<KuaiShouCampaign> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("campaign_id", campaignId);
        KuaiShouCampaign kuaiShouCampaign = kuaiShouCampaignMapper.selectOne(queryWrapper);
        KuaishouBatchCampaignPreview campaignPreview = new KuaishouBatchCampaignPreview();
        campaignPreview.setAccountId(kuaiShouCampaign.getAccountId());
        campaignPreview.setCampaignName(kuaiShouCampaign.getCampaignName());
        campaignPreview.setCampaignId(campaignId);
        campaignPreview.setCampaignType(kuaiShouCampaign.getCampaignType());
        campaignPreview.setPutStatus(kuaiShouCampaign.getPutStatus());
        if (!Check.isNull(kuaiShouCampaign.getDayBudget()) && kuaiShouCampaign.getDayBudget() != 0) {
            campaignPreview.setDayBudget(kuaiShouCampaign.getDayBudget());
        }
        campaignPreview.setDayBudgetSchedule(kuaiShouCampaign.getDayBudgetSchedule());
        campaignPreview.setIsTime(2);
        campaignPreview.setBatchId(batchId);
        return campaignPreview;


    }

    /**
     * 插入预览信息
     *
     * @param
     * @return com.alibaba.fastjson.JSONObject
     * @throws
     * @author ZHAOXA
     */
    private void insertCampaignsAndGroups(Integer type, Long campaignId, JSONObject data, KuaishouBatchCampaignPreview campaignPreview, KuaishouBatchGroupPreview groupPreview, KuaishouBatchCreativePreview creativePreview) throws Exception {
        //定向包
        JSONArray targetIds = data.getJSONArray("targetIds");
        //应用数据
        JSONObject appList = data.getJSONObject("appList");
        //应用分配方式 1 按账户，2按广告计划，3按广告组
        Integer appAllocation = appList.getInteger("appAllocation");
        Integer appId = null;
        Long siteId = null;
        String url = null;
        JSONArray appArr = appList.getJSONArray("appArr");
        JSONArray urlArr = appList.getJSONArray("urlArr");
        boolean appNoNull = isNotNull(appArr, null, 1);
        boolean urlNoNull = isNotNull(urlArr, null, 1);

        //监测链接分配方式 1 按账户，2按广告计划，3按广告组
        Integer linkAllocation = appList.getInteger("linkAllocation");
        JSONArray clickTrackUrlList = appList.getJSONArray("clickUrlList");
        JSONArray actionbarClickUrlList = appList.getJSONArray("clickUrlActionList");
        boolean tracknotNull = isNotNull(clickTrackUrlList, null, 1);
        boolean barnotNull = isNotNull(actionbarClickUrlList, null, 1);
        String clickTrackUrl = null;
        String actionbarClickUrl = null;
        //按账户
        if (appAllocation == 1) {
            if (appNoNull) {
                appId = appArr.getJSONObject(0).getInteger("appId");
                siteId = appArr.getJSONObject(0).getLong("siteId");
            }
            if (urlNoNull) {
                url = urlArr.getString(0);
            }
        }
        if (linkAllocation == 1) {
            if (tracknotNull) {
                clickTrackUrl = clickTrackUrlList.getString(0);
            }
            if (barnotNull) {
                actionbarClickUrl = actionbarClickUrlList.getString(0);
            }
        }

        //素材数据
        JSONObject materialArray = data.getJSONObject("materialArray");
        //创意组
        JSONArray materialList = materialArray.getJSONArray("materialList");

        JSONObject materialInfo = materialArray.getJSONObject("materialInfo");
        //广告语匹配方式  1自定义,2按创意,3按创意组
        Integer matchingMethod = materialInfo.getInteger("matchingMethod");
        JSONArray descriptionList = materialArray.getJSONArray("descriptionList");
        if (!Check.isNull(descriptionList)) {
            //创意组匹配
            descriptionList = advertisingSlogan(descriptionList, materialList);
        }
        creativePreview.setAccountId(campaignPreview.getAccountId());
        //分组规则 1定向，2创意组
        int count = targetIds.size() * materialList.size();
        int appCount = targetIds.size() * materialList.size();
        if (NoEn.NO1.valueInt() == type) {
            //添加已有计划预览数据
            if (!Check.isNull(campaignId)) {
                campaignPreviewMapper.insert(campaignPreview);
            }
            /**
             *按照 定向包 分组
             * 计划总数 = 定向包数（targetIds）
             * 同一计划下广告组的定向包一样，创意不同
             */
            for (int i = 0; i < targetIds.size(); i++) {
                if (appAllocation == 2) {
                    if (appNoNull) {
                        appId = appArr.getJSONObject(i).getInteger("appId");
                        siteId = appArr.getJSONObject(i).getLong("siteId");
                    }
                    if (urlNoNull) {
                        url = urlArr.getString(i);
                    }
                }
                if (linkAllocation == 2) {
                    if (tracknotNull) {
                        clickTrackUrl = clickTrackUrlList.getString(i);
                    }
                    if (barnotNull) {
                        actionbarClickUrl = actionbarClickUrlList.getString(i);
                    }
                }
                if (Check.isNull(campaignId)) {
                    campaignPreview.setId(null);
                    campaignPreview.setCampaignName(getName(campaignPreview.getCampaignNameFormat(), targetIds.getLong(i), null, appId, null) + i);
                    campaignPreviewMapper.insert(campaignPreview);
                }
                for (int j = 0; j < materialList.size(); j++) {
                    if (appAllocation == 3) {
                        appCount--;
                        if (appNoNull) {
                            appId = appArr.getJSONObject(appCount).getInteger("appId");
                            siteId = appArr.getJSONObject(appCount).getLong("siteId");
                        }
                        if (urlNoNull) {
                            url = urlArr.getString(appCount);
                        }
                    }
                    if (linkAllocation == 3) {
                        count--;
                        if (tracknotNull) {
                            clickTrackUrl = clickTrackUrlList.getString(count);
                        }
                        if (barnotNull) {
                            actionbarClickUrl = actionbarClickUrlList.getString(count);
                        }
                    }
                    groupPreview.setId(null);
                    groupPreview.setAppId(appId);
                    groupPreview.setPlanId(campaignPreview.getId());
                    groupPreview.setTemplateId(targetIds.getLong(i));
                    groupPreview.setUnitName(getName(groupPreview.getUnitNameFormat(), targetIds.getLong(i), groupPreview.getSceneId(), appId, groupPreview.getUnitType()) + j);
                    groupPreview.setUrl(url);
                    if (!Check.isNull(groupPreview.getBidMax()) && !Check.isNull(groupPreview.getBidMin())) {
                        int bid = getRandom(groupPreview.getBidMax(), groupPreview.getBidMin());
                        if (Check.isNull(groupPreview.getBid())) {
                            groupPreview.setCpaBid(bid);
                        } else {
                            groupPreview.setBid(bid);
                        }
                    }
                    groupPreviewMapper.insert(groupPreview);
                    JSONObject material = materialList.getJSONObject(j);
                    JSONArray photoArr = material.getJSONArray("photoArr");
                    if (matchingMethod == 2) {
                        //创意匹配
                        descriptionList = advertisingSlogan(descriptionList, photoArr);
                    }
                    for (int k = 0; k < photoArr.size(); k++) {
                        creativePreview.setId(null);
                        creativePreview.setSiteId(siteId);
                        creativePreview.setClickTrackUrl(clickTrackUrl);
                        creativePreview.setActionbarClickUrl(actionbarClickUrl);
                        JSONObject photo = photoArr.getJSONObject(k);
                        JSONObject image = photo.getJSONObject("image");
                        creativePreview.setPlanId(campaignPreview.getId());
                        creativePreview.setGroupId(groupPreview.getId());
                        creativePreview.setPhotoId(photo.getString("photoId"));
                        creativePreview.setCreativeName(photo.getString("creativeName") + k);
                        creativePreview.setImageUrl(image.getString("url"));
                        creativePreview.setImageSignature(image.getString("signature"));
                        if (matchingMethod == 1) {
                            creativePreview.setDescription(photo.getString("description"));
                        } else if (matchingMethod == 2) {
                            creativePreview.setDescription(descriptionList.getString(k));
                        } else if (matchingMethod == 3) {
                            creativePreview.setDescription(descriptionList.getString(j));
                        }
                        creativePreviewMapper.insert(creativePreview);
                    }
                }
            }
        } else if (NoEn.NO2.valueInt() == type) {
            /**
             *按照 创意组 分组
             * 计划总数 = 创意组数
             * 则同一广告计划内的创意完全相同,定向包不同
             */
            for (int i = 0; i < materialList.size(); i++) {
                if (appAllocation == 2) {
                    if (appNoNull) {
                        appId = appArr.getJSONObject(i).getInteger("appId");
                        siteId = appArr.getJSONObject(i).getLong("siteId");
                    }
                    if (urlNoNull) {
                        url = urlArr.getString(i);
                    }
                }
                if (linkAllocation == 2) {
                    if (tracknotNull) {
                        clickTrackUrl = clickTrackUrlList.getString(i);
                    }
                    if (barnotNull) {
                        actionbarClickUrl = actionbarClickUrlList.getString(i);
                    }
                }
                campaignPreview.setId(null);
                campaignPreview.setCampaignName(getName(campaignPreview.getCampaignNameFormat(), null, null, appId, null) + i);
                campaignPreviewMapper.insert(campaignPreview);
                JSONObject material = materialList.getJSONObject(i);
                JSONArray photoArr = material.getJSONArray("photoArr");
                if (matchingMethod == 2) {
                    //创意匹配
                    descriptionList = advertisingSlogan(descriptionList, photoArr);
                }
                for (int j = 0; j < targetIds.size(); j++) {
                    if (appAllocation == 3) {
                        appCount--;
                        if (appNoNull) {
                            appId = appArr.getJSONObject(appCount).getInteger("appId");
                            siteId = appArr.getJSONObject(appCount).getLong("siteId");
                        }
                        if (urlNoNull) {
                            url = urlArr.getString(appCount);
                        }
                    }
                    if (linkAllocation == 3) {
                        count--;
                        if (tracknotNull) {
                            clickTrackUrl = clickTrackUrlList.getString(count);
                        }
                        if (barnotNull) {
                            actionbarClickUrl = actionbarClickUrlList.getString(count);
                        }
                    }
                    groupPreview.setId(null);
                    groupPreview.setAppId(appId);
                    groupPreview.setPlanId(campaignPreview.getId());
                    groupPreview.setTemplateId(targetIds.getLong(j));
                    groupPreview.setUnitName(getName(groupPreview.getUnitNameFormat(), targetIds.getLong(j), groupPreview.getSceneId(), appId, groupPreview.getUnitType()) + j);
                    groupPreview.setUrl(url);
                    if (!Check.isNull(groupPreview.getBidMax()) && !Check.isNull(groupPreview.getBidMin())) {
                        int bid = getRandom(groupPreview.getBidMax(), groupPreview.getBidMin());
                        if (Check.isNull(groupPreview.getBid())) {
                            groupPreview.setCpaBid(bid);
                        } else {
                            groupPreview.setBid(bid);
                        }
                    }
                    groupPreviewMapper.insert(groupPreview);
                    for (int k = 0; k < photoArr.size(); k++) {
                        creativePreview.setId(null);
                        creativePreview.setSiteId(siteId);
                        creativePreview.setClickTrackUrl(clickTrackUrl);
                        creativePreview.setActionbarClickUrl(actionbarClickUrl);
                        JSONObject photo = photoArr.getJSONObject(k);
                        JSONObject image = photo.getJSONObject("image");
                        creativePreview.setPlanId(campaignPreview.getId());
                        creativePreview.setGroupId(groupPreview.getId());
                        creativePreview.setPhotoId(photo.getString("photoId"));
                        creativePreview.setCreativeName(photo.getString("creativeName") + k);
                        creativePreview.setImageUrl(image.getString("url"));
                        creativePreview.setImageSignature(image.getString("signature"));
                        if (matchingMethod == 1) {
                            creativePreview.setDescription(photo.getString("description"));
                        } else if (matchingMethod == 2) {
                            creativePreview.setDescription(descriptionList.getString(k));
                        } else if (matchingMethod == 3) {
                            creativePreview.setDescription(descriptionList.getString(i));
                        }
                        creativePreviewMapper.insert(creativePreview);
                    }
                }
            }
        }

    }

    /**
     * 判断非空
     *
     * @param
     * @return boolean
     * @throws
     * @author ZHAOXA
     */
    private boolean isNotNull(JSONArray arr, JSONArray arr2, Integer num) {
        if (num == 2) {
            return !CollectionUtils.isEmpty(arr) && !CollectionUtils.isEmpty(arr2);
        } else {
            return !CollectionUtils.isEmpty(arr);
        }
    }

    /**
     * 广告语整理
     *
     * @param
     * @return com.alibaba.fastjson.JSONArray
     * @throws
     * @author ZHAOXA
     */
    private static JSONArray advertisingSlogan(JSONArray descriptionList, JSONArray materialList) {
        if (materialList.size() <= descriptionList.size()) {
            return descriptionList;
        }
        JSONArray other = new JSONArray();
        if (materialList.size() > descriptionList.size()) {
            int num = materialList.size() / descriptionList.size();
            for (int i = 0; i <= num; i++) {
                other.addAll(descriptionList);
            }
        }
        return other;
    }

    /**
     * 整理通用广告计划数据
     *
     * @param
     * @return cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCampaignPreview
     * @throws
     * @author ZHAOXA
     */
    private KuaishouBatchCampaignPreview commonCampaign(JSONObject campaignJson, String batchId) {
        KuaishouBatchCampaignPreview campaignPreview = new KuaishouBatchCampaignPreview();
        campaignPreview.setAccountId(campaignJson.getLong("accountId"));
        campaignPreview.setCampaignName(campaignJson.getString("campaignName"));
        campaignPreview.setCampaignNameFormat(campaignJson.getString("campaignName"));
        campaignPreview.setCampaignType(campaignJson.getInteger("campaignType"));
        if (!Check.isNull(campaignJson.getLong("dayBudget")) && campaignJson.getLong("dayBudget") != 0) {
            campaignPreview.setDayBudget(campaignJson.getLong("dayBudget"));
        }
        campaignPreview.setDayBudgetSchedule(campaignJson.getString("dayBudgetSchedule"));
        campaignPreview.setTimeStart(campaignJson.getString("timeStart"));
        campaignPreview.setPutStatus(campaignJson.getInteger("campaignStatus"));
        campaignPreview.setIsTime(campaignJson.getInteger("isTime"));
        campaignPreview.setBatchId(batchId);
        return campaignPreview;
    }

    /**
     * 整理通用广告组数据
     *
     * @param
     * @return cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchGroupPreview
     * @throws
     * @author ZHAOX A
     */
    private KuaishouBatchGroupPreview commonGroup(JSONObject groupJson, String batchId, JSONObject campaignJson) {
        KuaishouBatchGroupPreview groupPreview = new KuaishouBatchGroupPreview();
        groupPreview.setAccountId(groupJson.getLong("accountId"));
        groupPreview.setUnitName(groupJson.getString("unitName"));
        groupPreview.setUnitNameFormat(groupJson.getString("unitName"));
        groupPreview.setPutStatus(Check.isNull(campaignJson.getInteger("unitStatus")) || campaignJson.getInteger("unitStatus") == 2 ? 2 : null);
        groupPreview.setBidType(groupJson.getInteger("bidType"));
        groupPreview.setBidMax(groupJson.getInteger("bidMax"));
        groupPreview.setBidMin(groupJson.getInteger("bidMin"));
        int bid = -1;
        if (!Check.isNull(groupJson.getInteger("bidMin")) && !Check.isNull(groupJson.getInteger("bidMax"))) {
            bid = getRandom(groupJson.getInteger("bidMax"), groupJson.getInteger("bidMin"));
            if (bid > 0) {
                groupJson.put("bid", bid);
            }
        }

        if (groupJson.getInteger("bidType") == 10) {
            if (bid > 0) {
                groupPreview.setCpaBid(bid);
            } else {
                groupPreview.setCpaBid(groupJson.getInteger("cpaBid"));
            }
        } else {
            groupPreview.setBid(groupJson.getInteger("bid"));
        }
        groupPreview.setOcpxActionType(groupJson.getInteger("ocpxActionType"));
        groupPreview.setDeepConversionType(groupJson.getInteger("deepConversionType"));
        groupPreview.setDeepConversionBid(groupJson.getInteger("deepConversionBid"));
        if (!Check.isNull(groupJson.getInteger("dayBudget")) && groupJson.getInteger("dayBudget") != 0) {
            groupPreview.setDayBudget(groupJson.getInteger("dayBudget"));
        }
        groupPreview.setSpeed(groupJson.getInteger("speed"));
        groupPreview.setBeginTime(groupJson.getString("beginTime"));
        groupPreview.setEndTime(groupJson.getString("endTime"));
        groupPreview.setScheduleTime(groupJson.getString("scheduleTime"));
        groupPreview.setSceneId(groupJson.getString("sceneId"));
        groupPreview.setShowMode(groupJson.getInteger("showMode"));
        groupPreview.setUseAppMarket(groupJson.getInteger("useAppMarket"));
        groupPreview.setAppStore(groupJson.getString("appStore"));
        groupPreview.setBatchId(batchId);
        groupPreview.setUnitType(groupJson.getInteger("unitType"));
        return groupPreview;
    }

    private static int getRandom(int x, int y) {
        int num = -1;
        //说明：两个数在合法范围内，并不限制输入的数哪个更大一些
        if (x < 0 || y < 0) {
            return num;
        } else {
            int max = Math.max(x, y);
            int min = Math.min(x, y);
            int mid = max - min;//求差
            //产生随机数
            return (int) (Math.random() * (mid + 1)) + min;
        }
    }

    /**
     * 整理通用创意数据
     *
     * @param
     * @return cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCreativePreview
     * @throws
     * @author ZHAOXA
     */
    private KuaishouBatchCreativePreview commonCreative(JSONObject creativeJson, String batchId) {
        KuaishouBatchCreativePreview creativePreview = new KuaishouBatchCreativePreview();
        creativePreview.setActionBarText(creativeJson.getString("actionBarText"));
        creativePreview.setOverlayType(creativeJson.getString("overlayType"));
        creativePreview.setStickerTitle(creativeJson.getString("stickerTitle"));
        creativePreview.setCreativeTag(creativeJson.getString("creativeTag"));
        creativePreview.setCreativeCategory(creativeJson.getInteger("creativeCategory"));
        creativePreview.setBatchId(batchId);
        return creativePreview;
    }

    /**
     * @param content    通配符String
     * @param templateId 定向模板ID
     * @param sceneId    广告位置ID
     * @param appId      应用包id、渠道号
     * @param unitType   创意制作方式
     * @return
     */
    private String getName(String content, Long templateId, String sceneId, Integer appId, Integer unitType) {
        String reg = "\\{\\{(.+?)\\}\\}";
        List<String> params = getParams(reg, content);
        if (Check.isNull(params)) {
            return content;
        }
        Map<String, String> data = new HashMap<>();
        for (int i = 0; i < params.size(); i++) {
            String regName = params.get(i);
            if ("日期".equals(regName)) {
                data.put(regName, DateUtils.getNowDate("yyyy-MM-dd"));
            } else if ("定向包".equals(regName)) {
                if (!Check.isNull(templateId)) {
                    QueryWrapper<KuaishouTemplate> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("template_id", templateId);
                    KuaishouTemplate template = kuaishouTemplateService.getOne(queryWrapper);
                    data.put(regName, template.getTemplateName());
                }
            } else if ("广告位置".equals(regName)) {
                if (!Check.isNull(sceneId)) {
                    Integer sceneid = JSONObject.parseArray(sceneId).getInteger(0);
                    if (sceneid == 1 || sceneid == 5) {
                        data.put(regName, SceneIdEnum.getEnumById(sceneid).getName());
                    } else {
                        data.put(regName, "场景广告位");
                    }
                }
            } else if ("应用名称".equals(regName)) {
                if (!Check.isNull(appId)) {
                    QueryWrapper<KuaiShouAppList> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("app_id", appId);
                    KuaiShouAppList one = kuaiShouAppListService.getOne(queryWrapper);
                    if (!Check.isNull(one)) {
                        data.put(regName, one.getAppName());
                    }
                }
            } else if ("渠道号".equals(regName)) {
                if (!Check.isNull(appId)) {
                    QueryWrapper<KuaiShouAppList> queryWrapper = new QueryWrapper();
                    queryWrapper.eq("app_id", appId);
                    KuaiShouAppList one = kuaiShouAppListService.getOne(queryWrapper);
                    if (!Check.isNull(one)) {
                        data.put(regName, one.getAppVersion());
                    }
                }
            } else if ("创意制作方式".equals(regName)) {
                if (!Check.isNull(unitType)) {
                    data.put(regName, unitType == 4 ? "自定义" : "程序化创意2.0");
                }
            }
        }
        String text = parse(reg, content, data);
        return text;
    }


    public static String parse(String pattern, String content, Map<String, String> data) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);

        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            String key = m.group(1);
            String value = data.get(key);
            m.appendReplacement(sb, value == null ? "" : value);
        }
        m.appendTail(sb);
        return sb.toString();
    }

    /**
     * 根据正则表达式获取文本中的变量名列表
     *
     * @param pattern
     * @param content
     * @return
     */
    public static List<String> getParams(String pattern, String content) {
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(content);

        List<String> result = new ArrayList<String>();
        while (m.find()) {
            result.add(m.group(1));
        }
        return result;
    }


}
