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

import cn.com.ctop.common.module.utils.Check;
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.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.IKuaishouBatchCampaignPreviewService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 快手-广告计划预览信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-01-26
 */
@Service
public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<KuaishouBatchCampaignPreviewMapper, KuaishouBatchCampaignPreview> implements IKuaishouBatchCampaignPreviewService {


    @Autowired
    KuaishouBatchCampaignPreviewMapper campaignPreviewMapper;
    @Autowired
    KuaishouBatchGroupPreviewMapper groupPreviewMapper;
    @Autowired
    KuaishouBatchCreativePreviewMapper creativePreviewMapper;

    @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);
        obj.put("campaignList", campaignPreviewList);
        QueryWrapper<KuaishouBatchGroupPreview> groupWrapper = new QueryWrapper<>();
        groupWrapper.eq("batch_id", batchId).eq("account_id", accountId).orderByDesc("create_time");
        List<KuaishouBatchGroupPreview> groupPreviewList = groupPreviewMapper.selectList(groupWrapper);
        obj.put("groupList", groupPreviewList);
        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("creativeList", creativePreviewList);
        return obj;
    }

    @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("数据异常，未获取到广告计划数据");
        }
        KuaishouBatchCampaignPreview campaignPreview = commonCampaign(campaignJson, batchId);
        //组
        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("数据异常，未获取到应用数据");
        }
        //分组规则 1 定向 2 创意 3 落地页
        Integer type = campaignJson.getInteger("groupRule");
        insertCampaignsAndGroups(type, data, campaignPreview, groupPreview, creativePreview);
    }


    /**
     * 插入预览信息
     *
     * @param
     * @return com.alibaba.fastjson.JSONObject
     * @throws
     * @author ZHAOXA
     */
    private void insertCampaignsAndGroups(Integer type, 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;
        Integer 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).getInteger("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) {
            /**
             *按照 定向包 分组
             * 计划总数 = 定向包数（targetIds）
             * 同一计划下广告组的定向包一样，创意不同
             */
            for (int i = 0; i < targetIds.size(); i++) {
                if (appAllocation == 2) {
                    if (appNoNull) {
                        appId = appArr.getJSONObject(i).getInteger("appId");
                        siteId = appArr.getJSONObject(i).getInteger("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(campaignPreview.getCampaignName() + 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).getInteger("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(groupPreview.getUnitName() + j);
                    groupPreview.setUrl(url);
                    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).getInteger("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(campaignPreview.getCampaignName() + 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).getInteger("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(groupPreview.getUnitName() + j);
                    groupPreview.setUrl(url);
                    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);
                    }
                }
            }
        }
    }


    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.setCampaignType(campaignJson.getInteger("campaignType"));
        campaignPreview.setPutStatus(campaignJson.getInteger("campaignStatus"));
        campaignPreview.setDayBudget(campaignJson.getInteger("dayBudget"));
        campaignPreview.setDayBudgetSchedule(campaignJson.getString("dayBudgetSchedule"));
        campaignPreview.setTimeStart(campaignJson.getString("timeStart"));
        campaignPreview.setIsTime(campaignJson.getInteger("isTime"));
        campaignPreview.setBatchId(batchId);
        return campaignPreview;
    }

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

        if (groupJson.getInteger("bidType") == 10) {
            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"));
        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;
    }

}
