package com.xxl.job.executor.batch.service.impl;

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.executor.batch.entity.KuaiShouCampaign;
import com.xxl.job.executor.batch.entity.KuaiShouCreative;
import com.xxl.job.executor.batch.entity.KuaiShouGroup;
import com.xxl.job.executor.batch.entity.KuaiShouGroupTarget;
import com.xxl.job.executor.batch.mapper.KuaiShouGroupMapper;
import com.xxl.job.executor.batch.mapper.KuaiShouGroupTargetMapper;
import com.xxl.job.executor.batch.service.IKuaiShouCampaignService;
import com.xxl.job.executor.batch.service.IKuaiShouCreativeService;
import com.xxl.job.executor.batch.service.IKuaiShouGroupService;
import com.xxl.job.executor.constant.KuaishouInterfaceConstant;
import com.xxl.job.executor.utils.Check;
import com.xxl.job.executor.utils.HttpUtils;
import com.xxl.job.executor.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
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 KuaiShouGroupTargetMapper groupTargetMapper;
    private static ExecutorService executorService = Executors.newFixedThreadPool(10);
    @Autowired
    private IKuaiShouCreativeService creativeService;

    /**
     * 获取广告组
     *
     * @param accessToken
     * @param accountId
     */
    @Override
    public void getGroupList(String accessToken, Long accountId) {
        QueryWrapper<KuaiShouCampaign> campaignQueryWrapper = new QueryWrapper<>();
        campaignQueryWrapper.eq("account_id", accountId);
        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);
                }
            });
        }


    }


    private 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);
        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 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();
        }
    }

    private void addGroupV2(Long advertiserId, JSONArray details) {
        if (!Check.isNull(details)) {
            List<KuaiShouGroup> groups = 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 bid_type = detail.getInteger("bid_type");
                    Long bid = detail.getLong("bid");
                    Integer ocpx_action_type = detail.getInteger("ocpx_action_type");
                    Long unitId = detail.getLong("unit_id");
                    String unit_name = detail.getString("unit_name");
                    Integer status = detail.getInteger("status");
                    Integer put_status = detail.getInteger("put_status");

                    KuaiShouGroup group = new KuaiShouGroup();
                    group.setId("" + advertiserId + unitId);
                    group.setAccountId(advertiserId);
                    group.setCampaignId(detail.getLong("campaign_id"));
                    group.setUnitId(unitId);
                    group.setUnitName(unit_name);
                    group.setStatus(status);
                    group.setPutStatus(put_status);
                    group.setCreateChannel(detail.getInteger("create_channel"));
                    group.setReviewDetail(detail.getString("review_detail"));
                    group.setBidType(bid_type);
                    group.setBid(bid);
                    group.setCpaBid(detail.getLong("cpa_bid"));
                    group.setOcpxActionType(ocpx_action_type);
                    group.setDeepConversionType(detail.getInteger("deep_conversion_type"));
                    group.setDeepConversionBid(detail.getLong("deep_conversion_bid"));
                    group.setDayBudget(detail.getLong("day_budget"));
                    group.setSpeed(detail.getInteger("speed"));
                    group.setBeginTime(detail.getString("begin_time"));
                    group.setEndTime(detail.getString("end_time"));
                    group.setScheduleTime(detail.getString("schedule_time"));
                    group.setSceneId(detail.getJSONArray("scene_id") + "");
                    group.setShowMode(detail.getInteger("show_mode"));
                    group.setUnitType(detail.getInteger("unit_type"));
                    group.setUrlType(detail.getInteger("url_type"));
                    group.setUrl(detail.getString("url"));
                    group.setAppId(detail.getLong("app_id"));
                    group.setAppIconUrl(detail.getString("app_icon_url"));
                    group.setGroupCreateTime(detail.getString("create_time"));
                    group.setGroupUpdateTime(detail.getString("update_time"));
                    group.setConvertId(detail.getLong("convert_id"));
                    group.setUseAppMarket(detail.getInteger("use_app_market"));
                    group.setAppStore(detail.getJSONArray("app_store") + "");
                    group.setCreateTime(new Date());
                    group.setUpdateTime(new Date());
                    groups.add(group);

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

                        }
                        targets.add(groupTarget);
                    }
                }
            }
            if (!Check.isNull(groups)) {
                groupMapper.replaceBatch(groups);
            }
            if (!Check.isNull(targets)) {
                groupTargetMapper.replaceBatch(targets);
            }
        }
    }

}
