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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IUserAllocationService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.kuaishou.modules.ai.service.IKuaishouLandpagePackageService;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouGroupTemplate;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplateTarget;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouGroupTemplateMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupTemplateService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouTemplateTargetService;
import com.alibaba.fastjson.JSON;
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.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 创建组模板
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-12-15
 */
@Service
@Slf4j
public class KuaiShouGroupTemplateServiceImpl extends ServiceImpl<KuaiShouGroupTemplateMapper, KuaiShouGroupTemplate> implements IKuaiShouGroupTemplateService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private KuaiShouGroupTemplateMapper groupTemplateMapper;
    @Autowired
    private IKuaiShouImageGetService imageGetService;
    @Autowired
    private IKuaiShouMaterialUploadService uploadService;
    @Autowired
    private IKuaishouTemplateTargetService templateTargetService;
    @Autowired
    private IKuaiShouVideoGetService kuaiShouVideoGetService;
    static ExecutorService executorService = Executors.newFixedThreadPool(5);

    /**
     * 提交创建任务
     *
     * @param requestJson
     * @return
     * @throws Exception
     */
    @Override
    public JSONObject submitUnitTask(JSONObject requestJson) throws Exception {
        Long accountId = requestJson.getLong("accountId");
        if (Check.isNull(accountId)) {
            throw new Exception("accountId不能为空");
        }
        Long campaignId = requestJson.getLong("campaignId");
        if (Check.isNull(campaignId)) {
            throw new Exception("campaignId不能为空");
        }
        Integer createCount = requestJson.getInteger("createCount");
        if (Check.isNull(createCount)) {
            throw new Exception("创建数不能为空不能为空");
        }
        JSONArray photoArr = requestJson.getJSONArray("photoArr");
        if (Check.isNull(photoArr)) {
            throw new Exception("请选择需要创建的视频");
        }

        Integer imageCount = requestJson.getInteger("imageCount");

        Integer createType = requestJson.getInteger("createType"); // 创建类型 0 单品 1 混搭
        Integer unitType = requestJson.getInteger("unitType"); // 7程序化。4自定义
        List<List<String>> photoIdsList = null;
        if (unitType == 4) {
            if (Check.isNull(createType)) {
                throw new Exception("请选择创意创建方式混搭、单品");
            }

            if (createType == 0 && createCount != photoArr.size()) {
                throw new Exception("单品视频数量必须和创建数量保持一致");
            }

            if (createType == 1 && createCount * 15 != photoArr.size()) {
                throw new Exception("混搭视频数量必须和创建数量保持倍数关系");
            }
        } else {
            List<String> photoIds = JSONArray.parseObject(photoArr.toJSONString(), List.class);
            photoIdsList = Lists.newArrayList(Lists.partition(photoIds, imageCount));
            if (createCount != photoIdsList.size()) {
                throw new Exception("程序化视频数量必须和创建数量保持倍数关系");
            }
        }
        JSONObject returnJson = new JSONObject();
        String userId = requestJson.getString("userId");
        String unitName = requestJson.getString("unitName");
        Long template_id = requestJson.getLong("templateId");
        Integer bid_type = requestJson.getInteger("bidType");
        Integer use_app_market = requestJson.getInteger("useAppMarket");
        JSONArray app_store = requestJson.getJSONArray("appStore");
        Long bid = requestJson.getLong("bid");
        Long cpa_bid = requestJson.getLong("cpaBid");
        Integer ocpx_action_type = requestJson.getInteger("ocpxActionType");
        Integer deep_conversion_type = requestJson.getInteger("deepConversionType");
        Long deep_conversion_bid = requestJson.getLong("deepConversionBid");
        JSONArray scene_id = requestJson.getJSONArray("sceneId");
        Integer unit_type = requestJson.getInteger("unitType");
        String begin_time = requestJson.getString("beginTime");
        String end_time = requestJson.getString("endTime");
        String schedule_time = requestJson.getString("scheduleTime");
        Long day_budget = requestJson.getLong("dayBudget");
        Long convert_id = requestJson.getLong("convertId");
        Integer url_type = requestJson.getInteger("urlType");
        String url = requestJson.getString("url");
        Long app_id = requestJson.getLong("appId");
        Integer show_mode = requestJson.getInteger("showMode");
        Integer speed = requestJson.getInteger("speed");
        String click_track_url = requestJson.getString("clickTrackUrl");
        String actionbar_click_url = requestJson.getString("actionbarClickUrl");
        Integer creative_category = requestJson.getInteger("creativeCategory");
        JSONArray creative_tag = requestJson.getJSONArray("creativeTag");
        String creative_name = requestJson.getString("creativeName");
        String action_bar_text = requestJson.getString("actionBarText");
        String description = requestJson.getString("description");
        String site_id = requestJson.getString("siteId");
        String schema_uri = requestJson.getString("schemaUri");
        String product_id = requestJson.getString("productId");
        String outer_id = requestJson.getString("outerId");
        Integer detail_unit_type = requestJson.getInteger("detailUnitType");
        Long library_id = requestJson.getLong("libraryId");
        Integer startNumber = 0;
        if (unitName.contains("{{序号}}")) {
            if (!Check.isNull(requestJson.getInteger("startNumber"))) {
                startNumber = requestJson.getInteger("startNumber");
            }
        }

        List<KuaiShouGroupTemplate> templates = new ArrayList<>();
        for (int i = 0; i < createCount; i++) {
            KuaiShouGroupTemplate template = new KuaiShouGroupTemplate();
            template.setCreateType(createType);
            if (!Check.isNull(createType) && createType == 0) { // 创建方式为单品
                Long photoId = photoArr.getLong(i);
                template.setPhotoId(photoId);
            } else if (!Check.isNull(createType) && createType == 1) { // 创建方式为混搭
                JSONArray photoIds = getPhotoIds(photoArr, i);
                if (Check.isNull(photoIds)) {
                    log.error("根据下标未获取到详细信息");
                    continue;
                }
                template.setPhotoIds(photoIds.toJSONString());
            } else {
                template.setPhotoIds(photoIdsList.get(i).toString());
            }
            String name = "";
            if (!unitName.contains("{{序号}}")) {
                name = unitName + "_" + i;
            } else {
                if (i == 0) {
                    name = unitName.replace("{{序号}}", String.valueOf(startNumber));
                } else {
                    name = unitName.replace("{{序号}}", String.valueOf(startNumber + i));
                }
            }

            template.setUnitName(name);
            template.setAccountId(accountId);
            template.setUserId(userId);
            template.setCampaignId(campaignId);

            if (!Check.isNull(template_id)) {
                template.setTemplateId(template_id);
            }
            if (!Check.isNull(bid_type)) {
                template.setBidType(bid_type);
            }
            if (!Check.isNull(use_app_market)) {
                template.setUseAppMarket(use_app_market);
            }
            if (!Check.isNull(app_store)) {
                template.setAppStore(app_store.toJSONString());
            }
            if (!Check.isNull(bid)) {
                template.setBid(bid);
            }
            if (!Check.isNull(cpa_bid)) {
                template.setCpaBid(cpa_bid);
            }
            if (!Check.isNull(ocpx_action_type)) {
                template.setOcpxActionType(ocpx_action_type);
            }
            if (!Check.isNull(deep_conversion_type)) {
                template.setDeepConversionType(deep_conversion_type);
            }
            if (!Check.isNull(deep_conversion_bid)) {
                template.setDeepConversionBid(deep_conversion_bid);
            }
            if (!Check.isNull(scene_id)) {
                template.setSceneId(scene_id.toJSONString());
            }
            if (!Check.isNull(unit_type)) {
                template.setUnitType(unit_type);
            }
            if (!Check.isNull(begin_time)) {
                template.setBeginTime(begin_time);
            }
            if (!Check.isNull(end_time)) {
                template.setEndTime(end_time);
            }
            if (!Check.isNull(schedule_time)) {
                template.setScheduleTime(schedule_time);
            }
            if (!Check.isNull(day_budget)) {
                template.setDayBudget(day_budget);
            }
            if (!Check.isNull(convert_id)) {
                template.setConvertId(convert_id);
            }
            if (!Check.isNull(url_type)) {
                template.setUrlType(url_type);
            }
            if (!Check.isNull(url)) {
                template.setUrl(url);
            }
            if (!Check.isNull(schema_uri)) {
                template.setSchemaUri(schema_uri);
            }
            if (!Check.isNull(app_id)) {
                template.setAppId(app_id);
            }
            if (!Check.isNull(show_mode)) {
                template.setShowMode(show_mode);
            }
            if (!Check.isNull(speed)) {
                template.setSpeed(speed);
            }
            if (!Check.isNull(click_track_url)) {
                template.setClickTrackUrl(click_track_url);
            }
            if (!Check.isNull(actionbar_click_url)) {
                template.setActionbarClickUrl(actionbar_click_url);
            }
            if (!Check.isNull(creative_category)) {
                template.setCreativeCategory(creative_category);
            }
            if (!Check.isNull(creative_tag)) {
                template.setCreativeTag(creative_tag.toJSONString());
            }
            if (!Check.isNull(creative_name)) {
                template.setCreativeName(creative_name);
            }
            if (!Check.isNull(action_bar_text)) {
                template.setActionBarText(action_bar_text);
            }
            if (!Check.isNull(description)) {
                template.setDescription(description);
            }
            if (!Check.isNull(description)) {
                template.setDescription(description);
            }
            if (!Check.isNull(site_id)) {
                template.setSiteId(site_id);
            }
            if (!Check.isNull(product_id)) {
                template.setProductId(product_id);
            }
            if (!Check.isNull(outer_id)) {
                template.setOuterId(outer_id);
            }
            if (!Check.isNull(detail_unit_type)) {
                template.setDetailUnitType(detail_unit_type);
            }
            if (!Check.isNull(library_id)) {
                template.setLibraryId(library_id);
            }
            template.setImageCount(imageCount);
            template.setTaskStatus(0);
            template.setCreativeReviewDetail("创意待创建");
            template.setCreativeStatus(0);
            templates.add(template);
        }
        boolean b = this.saveBatch(templates);
        if (b) {
            returnJson.put("code", 0);
            returnJson.put("size", templates.size());
        } else {
            returnJson.put("code", -1);
            returnJson.put("message", "提交任务失败");
        }

        return returnJson;
    }

    private JSONArray getPhotoIds(JSONArray photoArr, Integer index) {
        JSONArray array = new JSONArray();
        Integer minIndex;
        Integer maxIndex;
        if (index == 0) {
            maxIndex = (index + 1) * 15 - 1;
            minIndex = index;
        } else {
            maxIndex = (index + 1) * 15 - 1;
            minIndex = index * 15;
        }
        for (int i = 0; i < photoArr.size(); i++) {
            if (minIndex > maxIndex) {
                break;
            }
            Long photoId = photoArr.getLong(minIndex);
            array.add(photoId);
            minIndex++;
        }
        return array;
    }


    /**
     * 创建组
     */
    @Override
    public void createUnit(KuaiShouGroupTemplate template) {
        Long accountId = template.getAccountId();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        if (Check.isNull(token)) {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail("未获取到授权信息");
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("未获取到授权信息");
            updateById(updateTemplate);
            return;
        }
        JSONObject createUnitJson = new JSONObject();
        JSONArray sceneIdArr = JSONArray.parseArray(template.getSceneId());
        if (Check.isNull(sceneIdArr)) {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail("scene_id不能为空");
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("组创建失败");
            updateById(updateTemplate);
            return;
        }
        createUnitJson.put("scene_id", sceneIdArr); //资源位置
        Integer sceneId = (Integer) sceneIdArr.get(0);
        if (sceneId != 5) {
            if (!Check.isNull(template.getTemplateId())) {
                createUnitJson.put("template_id", template.getTemplateId());
            }
        } else {
            if (!Check.isNull(template.getTemplateId())) {
                JSONObject unionJson = getUnionJson(template.getTemplateId());
                if (unionJson.getInteger("code") != 0) {
                    updateTemplate.setTaskStatus(3);
                    updateTemplate.setReviewDetail(unionJson.getString("message"));
                    updateTemplate.setCreativeStatus(3);
                    updateTemplate.setCreativeReviewDetail("组创建失败");
                    updateById(updateTemplate);
                    return;
                } else {
                    createUnitJson.put("target", unionJson.getJSONObject("target"));
                }
            }
        }
        createUnitJson.put("campaign_id", template.getCampaignId());
        createUnitJson.put("unit_name", template.getUnitName());
        if (!Check.isNull(template.getBidType())) {
            createUnitJson.put("bid_type", template.getBidType()); // 优化目标类型
        }
        if (!Check.isNull(template.getUseAppMarket())) {
            createUnitJson.put("use_app_market", template.getUseAppMarket()); //优先从系统应用商店下载
        }
        if (!Check.isNull(template.getAppStore())) {
            createUnitJson.put("app_store", JSONArray.parseArray(template.getAppStore())); //应用商店列表
        }
        if (!Check.isNull(template.getBid())) {
            createUnitJson.put("bid", template.getBid()); //出价
        }
        if (!Check.isNull(template.getCpaBid())) {
            createUnitJson.put("cpa_bid", template.getCpaBid()); //出价
        }
        if (!Check.isNull(template.getOcpxActionType())) {
            createUnitJson.put("ocpx_action_type", template.getOcpxActionType()); //优化目标
        }
        if (!Check.isNull(template.getDeepConversionType())) {
            createUnitJson.put("deep_conversion_type", template.getDeepConversionType()); //深度转化目标
        }
        if (!Check.isNull(template.getDeepConversionBid())) {
            createUnitJson.put("deep_conversion_bid", template.getDeepConversionBid()); //深度转化目标出价
        }
        if (!Check.isNull(template.getBeginTime())) {
            createUnitJson.put("begin_time", template.getBeginTime()); //投放开始时间
        }
        if (!Check.isNull(template.getEndTime())) {
            createUnitJson.put("end_time", template.getEndTime()); //投放结束时间
        }
        if (!Check.isNull(template.getScheduleTime())) {
            createUnitJson.put("schedule_time", template.getScheduleTime()); //投放时间段
        }
        if (!Check.isNull(template.getDayBudget())) {
            createUnitJson.put("day_budget", template.getDayBudget()); //单日预算金额
        }
        if (!Check.isNull(template.getConvertId())) {
            createUnitJson.put("convert_id", template.getConvertId()); //转化目标ID
        }
        if (!Check.isNull(template.getUrlType())) {
            createUnitJson.put("url_type", template.getUrlType()); //url类型
        }
        if (!Check.isNull(template.getUrl())) {
            createUnitJson.put("url", template.getUrl()); // 投放链接
        }
        if (!Check.isNull(template.getSchemaUri())) {
            createUnitJson.put("schema_uri", template.getSchemaUri()); // 吊起链接
        }

        if (!Check.isNull(template.getAppId())) {
            createUnitJson.put("app_id", template.getAppId()); // 应用ID
        }
        if (!Check.isNull(template.getShowMode())) {
            createUnitJson.put("show_mode", template.getShowMode()); // 创意展现方式
        }
        if (!Check.isNull(template.getSpeed())) {
            createUnitJson.put("speed", template.getSpeed()); // 投放方式
        }
        if (!Check.isNull(template.getUnitType())) {
            createUnitJson.put("unit_type", template.getUnitType()); //创意制作方式
        }

        Long libraryId = template.getLibraryId();
        if (!Check.isNull(libraryId)) {
            JSONObject dpa_unit_param = new JSONObject();
            dpa_unit_param.put("library_id", libraryId);
            String productId = template.getProductId();
            if (!Check.isNull(productId)) {
                dpa_unit_param.put("product_id", productId);
            }
            String outerId = template.getOuterId();
            if (!Check.isNull(outerId)) {
                dpa_unit_param.put("outer_id", outerId);
            }
            Integer detailUnitType = template.getDetailUnitType();
            if (!Check.isNull(detailUnitType)) {
                dpa_unit_param.put("detail_unit_type", detailUnitType);
            }
            dpa_unit_param.put("dpa_unit_sub_type", 2);
            createUnitJson.put("dpa_unit_param", dpa_unit_param);
        }
        Map<String, Object> groupMap = iKuaishouInterfaceService.adUnitCreate(token.getAccessToken(), accountId, createUnitJson, 1);
        updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        Integer code = (Integer) groupMap.get("code");
        if (code == 0) {
            updateTemplate.setTaskStatus(2);
            Long unit = (Long) groupMap.get("unitId");
            updateTemplate.setUnitId((unit));
            if (template.getUnitType() == 4) {
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        createCreative(token.getAccessToken(), unit, template);
                    }
                };
                thread.start();
            } else {
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        createProgramCreative(token.getAccessToken(), unit, template);
                    }
                };
                thread.start();
            }
        } else {
            updateTemplate.setTaskStatus(3);
            updateTemplate.setReviewDetail((String) groupMap.get("message"));
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("组创建失败");
        }
        updateById(updateTemplate);
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据模板id 获取联盟定向
     *
     * @return
     */
    @Override
    public JSONObject getUnionJson(Long templateId) {
        JSONObject returnJson = new JSONObject();
        QueryWrapper<KuaishouTemplateTarget> targetQueryWrapper = new QueryWrapper<>();
        targetQueryWrapper.eq("template_id", templateId);
        targetQueryWrapper.last("limit 1");
        KuaishouTemplateTarget templateTarget = templateTargetService.getOne(targetQueryWrapper);
        if (Check.isNull(templateTarget)) {
            returnJson.put("code", -1);
            returnJson.put("message", "根据模板id未获取到模板详情");
            return returnJson;
        }
        JSONObject target = new JSONObject();
        if (!Check.isNull(templateTarget.getRegion())) {
            target.put("region", JSONArray.parseArray(templateTarget.getRegion()));
        }

        if (!Check.isNull(templateTarget.getMax()) && !Check.isNull(templateTarget.getMin())) {
            JSONObject ageJson = new JSONObject();
            if (!Check.isNull(templateTarget.getMax())) {
                ageJson.put("max", templateTarget.getMax());
            }
            if (!Check.isNull(templateTarget.getMin())) {
                ageJson.put("min", templateTarget.getMin());
            }
            target.put("age", ageJson);
        }
        if (!Check.isNull(templateTarget.getAgesRange())) {
            target.put("ages_range", JSONArray.parseArray(templateTarget.getAgesRange()));
        }

        if (!Check.isNull(templateTarget.getGender())) {
            target.put("gender", templateTarget.getGender());
        }

        if (!Check.isNull(templateTarget.getPlatformOs())) {
            target.put("platform_os", templateTarget.getPlatformOs());
        }

        if (!Check.isNull(templateTarget.getAndroidOsv())) {
            target.put("android_osv", templateTarget.getAndroidOsv());
        }

        if (!Check.isNull(templateTarget.getIosOsv())) {
            target.put("ios_osv", templateTarget.getIosOsv());
        }

        if (!Check.isNull(templateTarget.getNetwork())) {
            target.put("network", templateTarget.getNetwork());
        }

        if (!Check.isNull(templateTarget.getDeviceBrand())) {
            target.put("device_brand", JSONArray.parseArray(templateTarget.getDeviceBrand()));
        }

        if (!Check.isNull(templateTarget.getDevicePrice())) {
            target.put("device_price", JSONArray.parseArray(templateTarget.getDevicePrice()));
        }

        if (!Check.isNull(templateTarget.getAppInterest())) {
            target.put("app_interest", JSONArray.parseArray(templateTarget.getAppInterest()));
        }
        if (!Check.isNull(templateTarget.getFilterConvertedLevel())) {
            target.put("filter_converted_level", templateTarget.getFilterConvertedLevel());
        }

        JSONArray appIds = JSONArray.parseArray(templateTarget.getAppIds());
        if (!Check.isNull(appIds) && !appIds.isEmpty()) {
            target.put("app_ids", appIds);
        }

        JSONArray population = JSONArray.parseArray(templateTarget.getPopulation());
        if (!Check.isNull(population) && !population.isEmpty()) {
            target.put("population", population);
        }

        JSONArray excludePopulation = JSONArray.parseArray(templateTarget.getExcludePopulation());
        if (!Check.isNull(excludePopulation) && !excludePopulation.isEmpty()) {
            target.put("exclude_population", excludePopulation);
        }

        JSONArray paidAudience = JSONArray.parseArray(templateTarget.getPaidAudience());
        if (!Check.isNull(paidAudience) && !paidAudience.isEmpty()) {
            target.put("paid_audience", paidAudience);
        }
        //智能扩量
        JSONObject intelliExtendJson = new JSONObject();
        if (!Check.isNull(templateTarget.getIsOpen())) {
            intelliExtendJson.put("is_open", templateTarget.getIsOpen());
        }
        if (!Check.isNull(templateTarget.getNoAgeBreak())) {
            intelliExtendJson.put("no_age_break", templateTarget.getNoAgeBreak());
        }
        if (!Check.isNull(templateTarget.getNoGenderBreak())) {
            intelliExtendJson.put("no_gender_break", templateTarget.getNoGenderBreak());
        }
        if (!Check.isNull(templateTarget.getNoAreaBreak())) {
            intelliExtendJson.put("no_area_break", templateTarget.getNoAreaBreak());
        }
        if (!Check.isNull(intelliExtendJson)) {
            target.put("intelli_extend", intelliExtendJson);
        }
        //-------------兴趣行为定向
    /*    JSONObject behaviorInterest = new JSONObject();
        JSONObject behavior = new JSONObject();
        JSONObject interest = new JSONObject();*/
 /*       if (!Check.isNull(templateTarget.getKeyword())) {
            behavior.put("keyword", JSONArray.parseArray(templateTarget.getKeyword()));
        }
        if (!Check.isNull(templateTarget.getLabel())) {
            behavior.put("label", JSONArray.parseArray(templateTarget.getLabel()));
        }
        if (!Check.isNull(templateTarget.getStrengthType())) {
            behavior.put("strength_type", templateTarget.getStrengthType());
        }
        if (!Check.isNull(templateTarget.getTimeType())) {
            behavior.put("time_type", templateTarget.getTimeType());
        }
        if (!Check.isNull(templateTarget.getSceneType())) {
            behavior.put("scene_type", JSONArray.parseArray(templateTarget.getSceneType()));
        }
        if (!Check.isNull(templateTarget.getInterestLabel())) {
            interest.put("label", JSONArray.parseArray(templateTarget.getInterestLabel()));
        }
        if (!Check.isNull(behavior)) {
            behaviorInterest.put("behavior", behavior);
        }
        if (!Check.isNull(interest)) {
            behaviorInterest.put("interest", interest);
        }
        if (!Check.isNull(behaviorInterest)) {
            target.put("behavior_interest", behaviorInterest);
        }*/
        returnJson.put("target", target);
        returnJson.put("code", 0);
        return returnJson;
    }

    @Override
    public List<Long> getIdList() {
        return groupTemplateMapper.getIdList();
    }

    /**
     * 获取商品信息
     *
     * @param accountId
     * @param accessToken
     * @param libraryId
     * @param page
     * @param pageSize
     * @param libraryName
     * @return
     */
    @Override
    public JSONObject productList(Long accountId, String accessToken, Long libraryId, Integer page, Integer pageSize, String libraryName) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/v1/dpa/product/list";
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Token", accessToken);
        Map<String, Object> param = new HashMap<>();
        param.put("advertiser_id", accountId);
        param.put("library_id", libraryId);
        if (!Check.isNull(libraryName)) {
            param.put("id_or_name", libraryName);
        }
        param.put("page_size", pageSize);
        param.put("page", page);

        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!Check.isNull(resultJson)) {
            JSONObject data = resultJson.getJSONObject("data");
            if (!Check.isNull(data)) {
                data.put("page_size", pageSize);
                data.put("page", page);
            }

        }
        return resultJson;
    }

    @Autowired
    private IUserAllocationService userAllocationService;

    @Override
    public JSONObject getLibraryConfig(Long accountId) {
        JSONObject returnJson = new JSONObject();
        UserAllocation userAllocation = userAllocationService.getByAccountId(accountId);
        Long projectId = userAllocation.getProjectId();
        JSONObject configJson = groupTemplateMapper.getConfig(projectId);
        if (Check.isNull(configJson)) {
            returnJson.put("isLibrary", false);
        } else {
            Long libraryId = configJson.getLong("libraryId");
            returnJson.put("isLibrary", true);
            returnJson.put("libraryId", libraryId);
        }
        return returnJson;
    }


    /**
     * 获取当天api创建创意数
     *
     * @param accountId
     * @param date
     * @return
     */
    @Override
    public Result<Object> getApiCreateCount(Long accountId, String date) {
        //自定义
        Integer ctmCount = groupTemplateMapper.getApiCreateCount(accountId, date, 4);
        //程序化
        Integer pgdCount = groupTemplateMapper.getApiCreateCount(accountId, date, 7);
        JSONObject obj = new JSONObject();
        obj.put("ctmCount", ctmCount);
        obj.put("pgdCount", pgdCount);
        return Result.ok(obj);

    }

    /**
     * 根据photoId 获取视频、封面链接
     *
     * @param photoId
     * @return
     */
    @Override
    public JSONObject getUrlByPhotoId(Long photoId) {
        return groupTemplateMapper.getUrlByPhotoId(photoId.toString());
    }

    /**
     * 创建创意
     *
     * @param accessToken
     * @param unitId
     * @param template
     */
    @Override
    public void createCreative(String accessToken, Long unitId, KuaiShouGroupTemplate template) {
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        updateTemplate.setCreativeStatus(1);
        updateTemplate.setCreativeReviewDetail("创意创建中");
        this.updateById(updateTemplate);
        JSONObject createJson = new JSONObject();
        createJson.put("unit_id", unitId);
        if (!Check.isNull(template.getClickTrackUrl())) {
            createJson.put("click_track_url", template.getClickTrackUrl());
        }
        if (!Check.isNull(template.getActionbarClickUrl())) {
            createJson.put("actionbar_click_url", template.getActionbarClickUrl());
        }
        if (!Check.isNull(template.getCreativeCategory())) {
            createJson.put("creative_category", template.getCreativeCategory());
        }
        if (!Check.isNull(template.getCreativeTag())) {
            createJson.put("creative_tag", JSONArray.parseArray(template.getCreativeTag()));
        }

        JSONArray descriptionList = JSONArray.parseArray(template.getDescription());
        JSONArray creatives = new JSONArray();
        Integer createType = template.getCreateType();
        if (createType == 0) { // 单品
            Long photoId = template.getPhotoId();
            JSONObject videoMd5Json = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
            if (Check.isNull(videoMd5Json)) {
                log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                this.updateById(updateTemplate);
                return;
            }
            Integer materialType = videoMd5Json.getInteger("materialType");
            String videoMd5 = videoMd5Json.getString("md5");
            List<JSONObject> imageList = groupTemplateMapper.getImageListByMd5(videoMd5, template.getImageCount());
            if (Check.isNull(imageList)) {
                JSONObject json = new JSONObject();
                json.put("creative_name", template.getCreativeName());
                json.put("photo_id", template.getPhotoId());
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", getOneDescription(descriptionList));
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            } else {
                for (int i = 0; i < imageList.size(); i++) {

                    JSONObject imageJson = imageList.get(i);
                    if (Check.isNull(imageJson)) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    String imageMd5 = imageJson.getString("md5");
                    String imageToken = getImageToken(imageMd5, template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (Check.isNull(imageToken)) {
                        continue;
                    }
                    json.put("image_token", imageToken);
                    json.put("creative_name", template.getCreativeName() + "_" + i);
                    json.put("photo_id", template.getPhotoId());
                    json.put("creative_material_type", materialType);
                    json.put("action_bar_text", template.getActionBarText());
                    json.put("description", getOneDescription(descriptionList));
                    if (!Check.isNull(template.getSiteId())) {
                        json.put("site_id", template.getSiteId());
                    }
                    creatives.add(json);
                }
            }
        } else if (createType == 1) {  // 混搭
            JSONArray array = JSONArray.parseArray(template.getPhotoIds());
            if (Check.isNull(array)) {
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到混搭素材信息");
                this.updateById(updateTemplate);
                return;
            }
            for (int i = 0; i < array.size(); i++) {
                Long photoId = array.getLong(i);
                JSONObject videoJson = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
                if (Check.isNull(videoJson)) {
                    log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                    updateTemplate.setCreativeStatus(3);
                    updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                    this.updateById(updateTemplate);
                    return;
                }
                String videoMd5 = videoJson.getString("md5");
                Integer materialType = videoJson.getInteger("materialType");
                JSONObject json = new JSONObject();
                JSONObject imageJson = groupTemplateMapper.getImageJsonByMd5(videoMd5);
                if (!Check.isNull(imageJson)) {
                    String imageToken = getImageToken(imageJson.getString("md5"), template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (!Check.isNull(imageToken)) {
                        json.put("image_token", imageToken);
                    }
                }
                json.put("creative_name", template.getCreativeName() + "_" + i);
                json.put("photo_id", photoId);
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", getOneDescription(descriptionList));
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            }
        }
        createJson.put("creatives", creatives);
        Map<String, Object> creativeMap = iKuaishouInterfaceService.batchCreativeCreate(accessToken, template.getAccountId(), createJson, 1, template.getUserId());
        Integer code = (Integer) creativeMap.get("code");
        if (code == 0) {
            updateTemplate.setCreativeStatus(2);
            updateTemplate.setCreativeReviewDetail("创意创建成功");
            updateTemplate.setCreateCreativeCount((Integer) creativeMap.get("count"));
        } else {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail((String) creativeMap.get("message"));
        }
        this.updateById(updateTemplate);
    }

    private String getOneDescription(JSONArray descriptionList) {
        if (!Check.isNull(descriptionList)) {
            int number = new Random().nextInt(descriptionList.size());
            return descriptionList.getString(number);
        }
        return null;
    }

    private void createProgramCreative(String accessToken, Long unitId, KuaiShouGroupTemplate template) {
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        updateTemplate.setCreativeStatus(1);
        updateTemplate.setCreativeReviewDetail("创意创建中");
        updateTemplate.setUnitId(unitId);
        this.updateById(updateTemplate);
        JSONObject createJson = new JSONObject();
        Long accountId = template.getAccountId();
        createJson.put("advertiser_id", accountId);
        createJson.put("unit_id", unitId);
        createJson.put("package_name", template.getCreativeName());

        JSONArray photoIds = JSONArray.parseArray(template.getPhotoIds());
        if (Check.isNull(photoIds)) {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("未获取到PhotoIds");
            this.updateById(updateTemplate);
            return;
        }
        //素材列表
        List<KuaiShouVideoGet> videos = kuaiShouVideoGetService.getVideoListByPhotoIds(photoIds, accountId);
        if (Check.isNull(videos) || videos.isEmpty()) {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail("未获取到素材信息");
            this.updateById(updateTemplate);
            return;
        }
        // 程序化视频数
        Integer imageCount = template.getImageCount();
        if (imageCount < 3) {
            log.error("视频数小于3个，不执行创建");
            return;
        }

        //落地页 ID
        if (!Check.isNull(template.getSiteId()) && !"-1".equals(template.getSiteId())) {
            createJson.put("site_id", template.getSiteId());
        }
        //行动号召按钮
        if (!Check.isNull(template.getActionBarText())) {
            createJson.put("action_bar", template.getActionBarText());
        }
        //第三方点击检测链接
        if (!Check.isNull(template.getClickTrackUrl())) {
            createJson.put("click_url", template.getClickTrackUrl());
        }
        //第三方 ActionBar 点击监控链接
        if (!Check.isNull(template.getActionbarClickUrl())) {
            createJson.put("actionbar_click_url", template.getActionbarClickUrl());
        }
        //创意分类 与创意标签同时传或同时不传
        if (!Check.isNull(template.getCreativeCategory())) {
            createJson.put("creative_category", template.getCreativeCategory());
            createJson.put("creative_tag", JSONArray.parseArray(template.getCreativeTag()));
        }
        //作品广告语
        createJson.put("captions", getCaptions(template.getDescription()));

        JSONArray photoList = new JSONArray();
        for (KuaiShouVideoGet video : videos) {
            JSONObject photo = new JSONObject();
            photo.put("photo_id", video.getPhotoId());//视频 ID
            photo.put("cover_image_token", null);//封面图片 token,通过上传图片接口获得，不传值则直接使用视频的首帧作为封面图片
            photo.put("creative_material_type", video.getMaterialType());//1：竖版视频 2：横版视频
            photoList.add(photo);
        }
        createJson.put("photo_list", photoList);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Map<String, Object> creativeMap = this.createProgramCreatives(accountId, accessToken, createJson, 1);
        Integer code = (Integer) creativeMap.get("code");
        if (code == 0) {
            updateTemplate.setCreativeStatus(2);
            updateTemplate.setCreativeReviewDetail("创建程序化2.0创意成功");
        } else {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail((String) creativeMap.get("message"));
        }
        this.updateById(updateTemplate);
    }

    /**
     * 创建程序化创意
     */
    private Map<String, Object> createProgramCreatives(Long accountId, String token, JSONObject creativeParams, int count) {
        Map<String, Object> returnMap = new HashMap<>();
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            headers.put("Access-Token", token);
            String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.PROGRAM_CREATE;
            String result = HttpUtils.kuaiShouhttpPostRequest(url, creativeParams.toJSONString(), headers);
            JSONObject resultJson = JSON.parseObject(result);
            if (Check.isNull(resultJson)) {
                log.error("程序化创意创意异常：api接口返回为空");
                returnMap.put("code", -1);
                returnMap.put("message", "程序化创意创意异常：api接口返回为空");
                returnMap.put("success", false);
                return returnMap;
            }
            Integer code = resultJson.getInteger("code");
            String message = resultJson.getString("message");
            Long unitId = creativeParams.getLong("unit_id");
            if (code == 0) {
                createLandPageAndUnit(creativeParams, resultJson.getJSONObject("data"));
                returnMap.put("code", 0);
                returnMap.put("message", "success");
                returnMap.put("success", true);
            } else {
                log.error("批量2.0创建程序化创意失败，入参：{}，返回结果：{}", creativeParams.toString(), resultJson.toString());
                if ("系统错误".equals(message) && count <= 4) {
                    log.info("第{}次重新创建程序化创意", count);
                    //系统错误，则重新执行
                    return createProgramCreatives(accountId, token, creativeParams, count + 1);
                }
                if (message.contains("过于频繁") && count <= 4) {
                    Thread.sleep(1000);
                    //该请求接口「/rest/openapi/v2/creative/advanced/program/create」过于频繁，则重新执行
                    return createProgramCreatives(accountId, token, creativeParams, count + 1);
                }
                returnMap.put("code", -1);
                returnMap.put("message", resultJson.getString("message"));
                returnMap.put("success", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行创建程序化创意异常", e);
            returnMap.put("code", -1);
            returnMap.put("message", "执行创建程序化创意异常");
            returnMap.put("success", false);
        }
        return returnMap;
    }

    /**
     * 绑定落地页与广告组、创意的关系
     */
    @Autowired
    private IKuaishouLandpagePackageService landpagePackageService;

    private void createLandPageAndUnit(JSONObject programJson, JSONObject data) {
        if (!Check.isNull(data) && !Check.isNull(programJson.getLong("site_id"))) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    landpagePackageService.createLandPageAndUnit(programJson.getLong("site_id"), data.getLong("creative_id"), programJson.getLong("unit_id"), programJson.getLong("advertiser_id"));
                }
            };
            thread.start();
        }
    }


    private String getImageToken(String md5, Long accountId, String accessToken, String url) {

        String imageToken = null;
        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("signature", md5);
        queryWrapper.last("limit 1");
        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
        if (!Check.isNull(imageGet)) {
            imageToken = imageGet.getImageToken();
        } else {
            imageToken = uploadService.kuauiShouImageUpload(url, md5, accountId, accessToken);
        }


        return imageToken;

    }


    /**
     * 获取程序化广告语
     */
    private JSONArray getCaptions(String description) {
        JSONArray jsonArray = JSONArray.parseArray(description);
        if (jsonArray.size() <= 3) {
            return jsonArray;
        }
        //重置顺序
        Collections.shuffle(jsonArray);
        JSONArray captions = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            captions.add(jsonArray.getString(i));
            if (captions.size() == 3) {
                break;
            }
        }
        return captions;
    }

    @Override
    public void createUnitAgain(KuaiShouGroupTemplate template) {
        CtopOauthToken token = tokenService.getTokenByAccountId(template.getAccountId());
        if (template.getUnitType() == 4) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    createCreativeAgain(token.getAccessToken(), template.getUnitId(), template);
                }
            };
            thread.start();
        } else {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    createProgramCreative(token.getAccessToken(), template.getUnitId(), template);
                }
            };
            thread.start();
        }
    }

    @Override
    public List<JSONObject> getUrlByPhotoIds(Long accountId, JSONArray photoIds) {
        return groupTemplateMapper.getUrlByPhotoIds(accountId, photoIds);
    }

    private void createCreativeAgain(String accessToken, Long unitId, KuaiShouGroupTemplate template) {
        KuaiShouGroupTemplate updateTemplate = new KuaiShouGroupTemplate();
        updateTemplate.setId(template.getId());
        updateTemplate.setCreativeStatus(1);
        updateTemplate.setCreativeReviewDetail("创意创建中");
        this.updateById(updateTemplate);
        JSONObject createJson = new JSONObject();
        createJson.put("unit_id", unitId);
        if (!Check.isNull(template.getClickTrackUrl())) {
            createJson.put("click_track_url", template.getClickTrackUrl());
        }
        if (!Check.isNull(template.getActionbarClickUrl())) {
            createJson.put("actionbar_click_url", template.getActionbarClickUrl());
        }
        if (!Check.isNull(template.getCreativeCategory())) {
            createJson.put("creative_category", template.getCreativeCategory());
        }
        if (!Check.isNull(template.getCreativeTag())) {
            createJson.put("creative_tag", JSONArray.parseArray(template.getCreativeTag()));
        }

        JSONArray creatives = new JSONArray();
        Integer createType = template.getCreateType();
        if (createType == 0) { // 单品
            Long photoId = template.getPhotoId();
            JSONObject videoMd5Json = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
            if (Check.isNull(videoMd5Json)) {
                log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                this.updateById(updateTemplate);
                return;
            }
            Integer materialType = videoMd5Json.getInteger("materialType");
            String videoMd5 = videoMd5Json.getString("md5");
            List<JSONObject> imageList = groupTemplateMapper.getImageListByMd5(videoMd5, template.getImageCount());
            if (Check.isNull(imageList)) {
                JSONObject json = new JSONObject();
                json.put("creative_name", template.getCreativeName());
                json.put("photo_id", template.getPhotoId());
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", template.getDescription());
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            } else {
                for (int i = 0; i < imageList.size(); i++) {
                    JSONObject imageJson = imageList.get(i);
                    if (Check.isNull(imageJson)) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    String imageMd5 = imageJson.getString("md5");
                    String imageToken = getImageToken(imageMd5, template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (Check.isNull(imageToken)) {
                        continue;
                    }
                    json.put("image_token", imageToken);
                    json.put("creative_name", template.getCreativeName() + "_" + i);
                    json.put("photo_id", template.getPhotoId());
                    json.put("creative_material_type", materialType);
                    json.put("action_bar_text", template.getActionBarText());
                    json.put("description", template.getDescription());
                    if (!Check.isNull(template.getSiteId())) {
                        json.put("site_id", template.getSiteId());
                    }
                    creatives.add(json);
                }
            }
        } else if (createType == 1) {  // 混搭
            JSONArray array = JSONArray.parseArray(template.getPhotoIds());
            if (Check.isNull(array)) {
                updateTemplate.setCreativeStatus(3);
                updateTemplate.setCreativeReviewDetail("未获取到混搭素材信息");
                this.updateById(updateTemplate);
                return;
            }
            for (int i = 0; i < array.size(); i++) {
                Long photoId = array.getLong(i);
                JSONObject videoJson = groupTemplateMapper.getMd5ByPhotoId(String.valueOf(photoId));
                if (Check.isNull(videoJson)) {
                    log.error("未获取到素材详细信息,accountId:{},unitId:{}", template.getAccountId(), unitId);
                    updateTemplate.setCreativeStatus(3);
                    updateTemplate.setCreativeReviewDetail("未获取到素材信息");
                    this.updateById(updateTemplate);
                    return;
                }
                String videoMd5 = videoJson.getString("md5");
                Integer materialType = videoJson.getInteger("materialType");
                JSONObject json = new JSONObject();
                JSONObject imageJson = groupTemplateMapper.getImageJsonByMd5(videoMd5);
                if (!Check.isNull(imageJson)) {
                    String imageToken = getImageToken(imageJson.getString("md5"), template.getAccountId(), accessToken, imageJson.getString("url"));
                    if (!Check.isNull(imageToken)) {
                        json.put("image_token", imageToken);
                    }
                }
                json.put("creative_name", template.getCreativeName() + "_" + i);
                json.put("photo_id", photoId);
                json.put("creative_material_type", materialType);
                json.put("action_bar_text", template.getActionBarText());
                json.put("description", template.getDescription());
                if (!Check.isNull(template.getSiteId())) {
                    json.put("site_id", template.getSiteId());
                }
                creatives.add(json);
            }
        }
        createJson.put("creatives", creatives);
        Map<String, Object> creativeMap = iKuaishouInterfaceService.batchCreativeCreate(accessToken, template.getAccountId(), createJson, 1, template.getUserId());
        Integer code = (Integer) creativeMap.get("code");
        if (code == 0) {
            updateTemplate.setCreativeStatus(2);
            updateTemplate.setCreativeReviewDetail("创意创建成功");
            updateTemplate.setCreateCreativeCount((Integer) creativeMap.get("count"));
        } else {
            updateTemplate.setCreativeStatus(3);
            updateTemplate.setCreativeReviewDetail((String) creativeMap.get("message"));
        }
        this.updateById(updateTemplate);
    }
}
